问题描述
我有一个 .Net 对象,我已将其序列化为 Xml,并使用 Xml 属性进行装饰.我现在想将相同的对象序列化为 Json,最好使用 Newtonsoft 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.
我想直接从内存中的 .Net 对象转到 Json 字符串(无需先序列化为 Xml).我不希望向类中添加任何 Json 属性,而是希望 Json 序列化程序使用现有的 Xml 属性.
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; }
}
变成
{
"foo":0,
"marco":0
}
推荐答案
原来这不是 Newtonsoft Json.Net 库的现有功能.我已经编写了一个补丁并将其上传到 Json.Net 问题跟踪器(存档链接 这里):
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 (archived link here):
这允许以下操作:
- XmlIgnore 的工作方式与 JsonIgnore 类似.
- XmlElementAttribute.ElementName 将更改 Json 属性名称.
- XmlType.AnonymousType 将禁止将对象打印到 Json(XmlContractResolver.SuppressAnonymousType 属性会改变这种行为)这有点 hacky,因为我一直在学习 Json.Net 的内部结构.
这篇关于将 .Net 对象序列化为 json,使用 xml 属性进行控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)