ServiceStack.Text如何序列化类JSON [英] ServiceStack.Text how to serialize class to JSon

查看:366
本文介绍了ServiceStack.Text如何序列化类JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚下载ServiceStack.Text在我的ASP.NET中使用它。我有许多属性类,并希望它们序列化(字符串,整数,二进制)的五到JSON。任何人都可以发表简单的例子,如何从我的类中创建JSON对象?

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?

推荐答案

ServiceStack将默认反序列化POCO的所有公共属性。

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

如果你只想序列化只是几个你想装饰使用[DataContract]类的属性,然后,[数据成员]属性(以同样的方式,你会如果您正在使用MS DataContractJsonSerializer),例如:

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; }
}

然后,您可以使用上JsonSerializer静态工具方法(德)序列化,或者更简洁扩展方法,例如:

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>();

编辑:

由于@Noah提到(从评论),您也可以使用[IgnoreDataMember]属性排除单个属性。

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

这篇关于ServiceStack.Text如何序列化类JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆