只序列化接口的属性,以JSON与Json.net [英] Serialize only interface properties to JSON with Json.net

查看:87
本文介绍了只序列化接口的属性,以JSON与Json.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过一个简单的类/接口这样

With a simple class/interface like this

public interface IThing
{
    string Name { get; set; }
}

public class Thing : IThing
{
    public int Id { get; set; }
    public string Name { get; set; }
}



我怎样才能获得JSON字符串只有名称属性( ?底层接口的唯一属性)

How can I get the JSON string with only the "Name" property (only the properties of the underlying interface) ?

其实,当我作出这样的:

Actually, when i make that :

var serialized = JsonConvert.SerializeObject((IThing)theObjToSerialize, Formatting.Indented);
Console.WriteLine(serialized);



我得到充分的对象JSON(编号+姓名);

I get the full object as JSON (Id + Name);

感谢的提前通过!

推荐答案

您可以使用条件序列化。看看这个链接。基本上,你需要实现 IContractResolver 接口,重载 ShouldSerialize 方法和你的解析器传递给了JSON的构造串行器。

You can use conditional serialization. Take a look at this link. Basicly, you need to implement the IContractResolver interface, overload the ShouldSerialize method and pass your resolver to the constructor of the Json Serializer.

这篇关于只序列化接口的属性,以JSON与Json.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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