生成嵌套的JSON

时间:2018-09-04 05:58:23

标签: c# json json.net

我想通过c#对象生成此嵌套的json

{
  "contest": {
    "name": "eatfast"
  },
  "contestants": {
    "player": [
      {
        "id": 1,
        "name": "KILL",
        "stats": {
          "time": 5
        }
      },
      {
        "id": 2,
        "name": "BILL",
        "stats": {
          "time": 16
        }
      }
    ]
  }
}

这里有我

private static string FormatJson(string json)
        {
            dynamic parsedJson = JsonConvert.DeserializeObject(json);
            return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
        }

private void button2_Click(object sender, EventArgs e)
{
    string json = "{\"contest\": { \"name\": \"eatfast\"},\"contestants\":  {\"player\": [";

    Contestants test = new Contestants
    {
        id = 3,
        name = "JESUS"
        //stats;
    };

    json = json + JsonConvert.SerializeObject(test, Formatting.Indented) + "]}}" ;
    System.IO.File.WriteAllText("test.txt", FormatJson(json));
}

输出

{
  "contest": {
    "name": "eatfast"
  },
  "contestants": {
    "player": [
      {
        "id": 3,
        "name": "JESUS"
      }
    ]
  }
}

在这个示例中,您能否给我一些有关如何添加玩家或如何增加统计时间的想法,请多多帮助

还是应该使用字符串操作手动进行操作?

1 个答案:

答案 0 :(得分:0)

根据评论,这就是您班级的样子(json2csharp.com

public class RootObject
{
    public Contest contest { get; set; }
    public Contestants contestants { get; set; }
}

public class Contest
{
    public string name { get; set; }
}   

public class Player
{
    public int id { get; set; }
    public string name { get; set; }
    public Stats stats { get; set; }
}

public class Stats
{
    public int time { get; set; }
}

public class Contestants
{
    public List<Player> player { get; set; }
}

接下来要做的就是使用Json.NET(可通过NuGet获得):

RootObject obj = JsonConvert.DeserializeObject<RootObject>(yourjsonString);

RootObject obj = new RootObject(); //proper initialisation of your object needed
string json = JsonConvert.SerializeObject(obj);