Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top