c# - 将 .Net 对象序列化为 json,使用 xml 属性控制

标签 c# xml-serialization json.net

我有一个 .Net 对象,我一直在将其序列化为 Xml,并使用 Xml 属性进行装饰。我现在想将同一个对象序列化为 Json,最好使用 Newtonsoft Json.Net图书馆。

我想直接从内存中的 .Net 对象转到 Json 字符串(无需先序列化为 Xml)。我不希望向该类添加任何 Json 属性,而是希望 Json 序列化程序使用现有的 Xml 属性。

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

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

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

成为

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

最佳答案

使用 [JsonProperty(PropertyName="foo")] 属性并设置 PropertyName

关于c# - 将 .Net 对象序列化为 json,使用 xml 属性控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686817/

相关文章:

c# - 条件 xml 序列化

java - JAXB 使用 ID 引用而不是包含来序列化 XML

c# - 如何在 Gridview 中将工具提示正确添加为悬停按钮

c# - 在 XWPFDocument 中插入新段落 (C# NPOI.OOXML)

c# - XmlSerializer : "The type ' Type' may not be used in this context"

c# - json.net 使用 CamelCasePropertyNamesContractResolver 错误地转换 TimeZoneInfo

c# - 在不更改 URI 模板反序列化的情况下使用自定义 WCF 正文反序列化

c# - 如何让 JavaScriptSerializer 将子对象视为普通的旧字符串?

c# - 是否可以创建多语言帮助 (.chm) 文件?

c# - 如何在 StackPanel 或 ListView 中叠加项目?