序列化.NET对象为JSON,使用XML属性控制 [英] Serialize .Net object to json, controlled using xml attributes

查看:170
本文介绍了序列化.NET对象为JSON,使用XML属性控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我被序列化到XML并装饰有XML属性.NET对象。我现在想序列相同的对象为JSON,最好使用 Newtonsoft Json.Net 库。



我想直接从.NET对象去在内存中一个JSON字符串(不序列化到XML在前)。我不希望添加任何的Json属性类,而是想为JSON序列化使用现有的XML属性。

 公共类世界{
[XmlIgnore]
公众诠释ignoreMe {搞定; }

[的XmlElement(富)]
公众诠释吧{搞定; }

[的XmlElement(马可)]
公众诠释马球{搞定; }
}



变为

  {
富:0,
马:0
}


解决方案

原来这不是Newtonsoft Json.Net库的现有功能。我写了一个补丁并将其上传到 Json.Net问题跟踪



这允许以下内容:




  • XmlIgnore作品就像JsonIgnore
  • $ b。 $ b
  • XmlElementAttribute.ElementName将改变JSON的属性名称。

  • XmlType.AnonymousType将抑制来自对象被打印到JSON(XmlContractResolver.SuppressAnonymousType属性会改变这种行为)的此有点哈克,因为我不得不学习Json.Net的内部,因为我一直都是去。


I have a .Net object which I've been serializing to Xml and is decorated with Xml attributes. I would now like to serialize the same object to Json, preferably using the Newtonsoft Json.Net library.

I'd like to go directly from the .Net object in memory to a Json string (without serializing to Xml first). I do not wish to add any Json attributes to the class, but instead would like for the Json serializer to use the existing Xml attributes.

public class world{
  [XmlIgnore]
  public int ignoreMe{ get; }

  [XmlElement("foo")]
  public int bar{ get; }

  [XmlElement("marco")]
  public int polo{ get; }
}

becomes

{
  "foo":0,
  "marco":0
}

解决方案

Turns out this wasn't an existing feature of the Newtonsoft Json.Net library. I've written a patch and uploaded it to the Json.Net issue tracker

This allows for the following:

  • XmlIgnore works just like JsonIgnore.
  • XmlElementAttribute.ElementName will alter the Json property name.
  • XmlType.AnonymousType will suppress objects from being printed to Json (XmlContractResolver.SuppressAnonymousType property alters this behaviour) this is a little bit hacky, as I've had to learn Json.Net's internals as I've been going.

这篇关于序列化.NET对象为JSON,使用XML属性控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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