Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...