ServiceStack.Text how to serialize class to JSon

白昼怎懂夜的黑 提交于 2020-01-09 10:22:43

问题


Just downloaded ServiceStack.Text to use it in my ASP.NET. I have class with many properties and would like to serialize five of them(string, integer, binary) to JSON. Could anyone post simple example how to create JSon object from my class?


回答1:


ServiceStack will deserialize all public properties of a POCO by default.

If you only want to serialize just a few of the properties then you want to decorate your class with [DataContract], [DataMember] attributes (in the same way you would if you were using MS DataContractJsonSerializer), e.g:

[DataContract]
public class MyClass
{
    public string WillNotSerializeString { get; set; }

    [DataMember]
    public string WillSerializeString { get; set; }

    [DataMember]
    public int WillSerializeInt { get; set; }

    [DataMember]
    public byte[] WillSerializeByteArray { get; set; }
}

Then you can use either the static utility methods on JsonSerializer to (De)serialize it, or the more terse extension methods, e.g:

var dto = new MyClass { WillSerializeString = "some text" };
string json = dto.ToJson();
MyClass fromJson = json.FromJson<MyClass>();

Edit:

As @Noah mentions (from comments) you can also use the [IgnoreDataMember] attribute to exclude a single property.




回答2:


You can use the [Serializable()] attribute on your custom class and then:

JavaScriptSerializer serializer = new JavaScriptSerializer();

var Json = serializer.Serialize(myObject);

To ignore specific properties in the object you're serializing, simply place the [NonSerialized] attribure on them.

Update:

Given that you want to use ServiceStack to do your serialization, the ServiceStack website gives the following example:

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);

Source: http://www.servicestack.net/mythz_blog/?p=344




回答3:


servicestack's test proves that by providing the [DataContract] and [DataMember] attribute allows you to determine which one is being serialized and which doesn't.

Test: https://github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/DataContractTests.cs

objects in test: https://github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/Support/DdnDtos.cs



来源:https://stackoverflow.com/questions/7307100/servicestack-text-how-to-serialize-class-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!