ServiceStack.Text how to serialize class to JSon ServiceStack.Text how to serialize class to JSon json json

ServiceStack.Text how to serialize class to JSon


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.


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


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