将 .Net 对象序列化为 json,使用 xml 属性进行控制

编程入门 行业动态 更新时间:2024-10-04 11:16:43
本文介绍了将 .Net 对象序列化为 json,使用 xml 属性进行控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 .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 属性进行控制

本文发布于:2023-11-29 15:24:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646791.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   属性   对象   Net   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!