对象中的多个json对象(json.net)

时间:2014-06-27 10:38:58

标签: json.net

是否可以获得这样的格式:

"list":{
  "one":{
    "fieldone":"-----",
    "fieldtwo":"-----"
   },
  "two":{
     "fieldone":"-----",
     "fieldtwo":"-----"
   }
 }

我不希望删除数组[]或名称“one”和“two”,我正在努力获得以下格式。

1 个答案:

答案 0 :(得分:0)

如果您将项目放入字典而不是列表中,那么您可以获得所需的结果。这是一个例子:

class Program
{
    static void Main(string[] args)
    {
        RootObject obj = new RootObject();
        obj.Items = new Dictionary<string, Item>();
        obj.Items.Add("one", new Item { FieldOne = "foo", FieldTwo = "bar" });
        obj.Items.Add("two", new Item { FieldOne = "fizz", FieldTwo = "bang" });

        string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
        Console.WriteLine(json);
    }
}

class RootObject
{
    [JsonProperty("list")]
    public Dictionary<string, Item> Items { get; set; }
}

class Item
{
    [JsonProperty("fieldone")]
    public string FieldOne { get; set; }
    [JsonProperty("fieldtwo")]
    public string FieldTwo { get; set; }
}

输出:

{
  "list": {
    "one": {
      "fieldone": "foo",
      "fieldtwo": "bar"
    },
    "two": {
      "fieldone": "fizz",
      "fieldtwo": "bang"
    }
  }
}