序列化JSON对象数组(Json.NET)

时间:2017-07-22 21:14:54

标签: c# json json.net

我正在学习JSON,并想知道如何创建一个对象数组。我希望我的JSON文件看起来像这样

{
    "Place": {
        "Stores": [{
            "Grocery": {
                "stock": "fruit",
                "distance": 19,
                "size": 12
            },
            "Department": {
                "stock": "clothing",
                "distance": 21,
                "size": 7
            }
        }]
    }
}

这是我的C#类看起来像

public class RootObject
{
    public Place Place { get; set; }
}

public class Place
{
    public List<Store> Stores { get; set; }
}

public class Store
{
    public Grocery Grocery { get; set; }
    public Department Department { get; set; }
}

public class Grocery
{
    public string stock { get; set; }
    public int distance { get; set; }
    public int size { get; set; }
}

public class Department
{
    public string stock { get; set; }
    public int distance { get; set; }
    public int size { get; set; }
}

到目前为止,我已经尝试过像这样编码,类似于newtonsoft网站上的示例

Rootobject root = new Rootobject
{
    Place = new Place
    {
        stores = new List<Store>
        {
            Grocery = new Grocery
            {
                stock ="fruit",
                distance = 19,
                size = 12
            },
            Department = new Department
            {
                stock ="clothing",
                distance = 21,
                size = 7
            }
        }
    }
};

string json = JsonConvert.SerializeObject(root,          
    Formatting.Indented,              
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\output.json", json);

但我在

收到两个CS0117错误
Grocery = new Grocery

Department = new Department

表示Store不包含Grocery / Department的定义

我在这里做错了什么?我只是在语法上犯了错误,还是有可能我只是接近以错误的方式序列化?非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您的对象应如下所示:

 Rootobject root = new Rootobject
    {
        Place = new Place
        {
            stores = new List<Store>
            {
                new Store{
                   Grocery = new Grocery
                  {
                    stock ="fruit",
                    distance = 19,
                    size = 12
                  },
                 Department = new Department
                {
                    stock ="clothing",
                    distance = 21,
                    size = 7
                }
               }
            }
        }
    };

我是从头开始写的,所以我希望语法很好。但主要的想法是你创建了商店列表,而不是列表中的任何商店。您应该使用new Store

创建一些商店