ServiceStack.Text how to serialize class to JSon

2019-01-18 11:59发布

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?

3条回答
仙女界的扛把子
2楼-- · 2019-01-18 12:18

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

查看更多
爷、活的狠高调
3楼-- · 2019-01-18 12:24

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

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-18 12:33

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.

查看更多
登录 后发表回答