简体   繁体   English

使用属性将C#中的对象转换为JSON

[英]Convert Object in C# to JSON with Attributes

I am trying to convert an object like the one below: 我正在尝试转换如下对象:

public class MyObject
{
    public ListOfStuff[] item { get; set; }
    public string Name { get; set; }
    public string Surname{ get; set; }
}

To a JSON object that looks like this: 对于如下所示的JSON对象:

{"listofstuff":[{
            "@stuffone":"1",
            "@stufftwo":"2",
            "@stuffthree":"3",
    }], 
"@name":"Bob",
"@surname":"The Builder"}

So that when it is converted to XML at a later stage the XML file is attribute centric rather than element centric. 因此,在以后将其转换为XML时,XML文件是以属性为中心,而不是以元素为中心。 The part I am having difficulty with is @attributes I am using Newtonsoft.JSON for my Serialization, exmaple of how I serializing in C# is below: 我遇到困难的部分是@attributes我正在使用Newtonsoft.JSON进行序列化,有关如何在C#中进行序列化的示例如下:

string myJSONObject = JsonConvert.SerializeObject(MyObject);

Thanks in advance for any help. 在此先感谢您的帮助。

You just need to use the [JsonProperty] attribute to specify the JSON name. 您只需要使用[JsonProperty]属性来指定JSON名称。 Here's an example (ignoring ListOfStuff for simplicity - apply the same approach): 这是一个示例(为简单起见,忽略ListOfStuff应用相同的方法):

using System;
using Newtonsoft.Json;

public class MyObject
{
    [JsonProperty("@name")]
    public string Name { get; set; }
    [JsonProperty("@surname")]
    public string Surname{ get; set; }
}

class Test
{
    static void Main()
    {
        var x = new MyObject { Name = "Bob", Surname = "The Builder" };
        Console.WriteLine(JsonConvert.SerializeObject(x));
    }
}

Output: 输出:

{"@name":"Bob","@surname":"The Builder"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM