C#解析Json有多个对象和数组newtonsoft

时间:2016-07-13 05:30:08

标签: c# arrays json json.net

我正在尝试使用C#中的newtonsoft解析一个相当复杂/不必要的复杂JSON输出但是由于某种原因我的解析器总是返回null。我已经搜索了所有的搜索结果,似乎无法找到解决方案。

我正在尝试解析的JSON文件示例:

{
  "success": 1,
  "d": {
    "gameData": {
      "MJ2Y7tDg": {
        "scores": [
          {
            "max": 1.83,
            "avg": 1.73,
            "rest": 2,
            "active": true,
            "scoreid": "2c556xv464x0x4vtqc"
          },
          {
            "max": 3.47,
            "avg": 3.24,
            "rest": 2,
            "active": true,
            "scoreid": "2c556xv498x0x0"
          },
          {
            "max": 6.06,
            "avg": 5.08,
            "rest": 1,
            "active": true,
            "scoreid": "2c556xv464x0x4vtqd"
          }
        ],
        "count": 62,
        "highlight": [
          false,
          true
        ]
      },
      "jZICYUQu": {
        "scores": [
          {
            "max": 2.25,
            "avg": 2.13,
            "rest": null,
            "active": true,
            "scoreid": "2c5guxv464x0x4vuiv"
          },
          {
            "max": 3.55,
            "avg": 3.29,
            "rest": null,
            "active": true,
            "scoreid": "2c5guxv498x0x0"
          },
          {
            "max": 3.9,
            "avg": 3.33,
            "rest": null,
            "active": true,
            "scoreid": "2c5guxv464x0x4vuj0"
          }
        ],
        "count": 62,
        "highlight": [
          false,
          false
        ]
      }
    }
  }
}

这是我到目前为止所做的,我对JSON争论很新:)

public class RootObject
    {
        public int success { get; set; }
        public List<d> d { get; set; }
    }

    public class d
    {
        public List<gameData> gameData { get; set; }
    }

    public class gameData
    {
        public IDictionary<string, Score> gameData{ get; set; }
        public List<scores[]> GameList;
    }
    public class Score
    {
        public double max { get; set; }
        public double avg { get; set; }
        public int rest { get; set; }
        public bool active { get; set; }
        public string scoreid { get; set; }
    }

任何拥有更多JSON争吵经验的人都知道如何使其工作?

谢谢先进。 P.S我目前在读高中,学习C#

1 个答案:

答案 0 :(得分:2)

解析器返回null,因为类的结构并不正确地类似于JSON的结构。类的正确结构是:

public class RootObject
{
    public int success { get; set; }
    public Class_d d { get; set; }
}

public class Class_d
{
    public Dictionary<string, GameData> gameData { get; set; }
}

public class GameData
{
    public List<Score> scores { get; set; }
    public int count { get; set; }
    public bool[] highlight { get; set; }
}

public class Score
{
    public decimal max { get; set; }
    public decimal avg { get; set; }
    public int? rest { get; set; }
    public bool active { get; set; }
    public string scoreid { get; set; }
}

您可以按如下方式使用它:

string json = "..."; // the JSON in your example
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);