可以使用名为numbers的对象反序列化此JSON

时间:2012-12-06 12:05:14

标签: c# json json.net

是否可以使用JSON.NET反序列化此json?

"players": {
        "0": {              
            "success": 1,               
            "name": "xsusususdd"
        },
        "1": {              
            "success": 1,               
            "name": "bleeps"
        },
       ..."n": {
               "success": 1,                
               "name": "bloops"
               }
       }

我正在使用的第三方Web服务不返回数组,而是返回由任意数量的嵌套对象组成的对象。

我从以下几点开始:

    public class Players
    {
      public Player 0 {get;set;} //cant name the Player 0
      public Player 1 {get;set;} //cant name the Player 1
      public List<Players> players {get;set;} //doesn't work because it isn't being returned as an array
    }


    public class Player
    {          
        public string success { get; set; }         
        public string name { get; set; }        
    }


  var URL = new WebClient().DownloadString("http://webservice");
  Players result = JsonConvert.DeserializeObject<Players>(URL);

2 个答案:

答案 0 :(得分:3)

您应该能够反序列化为Dictionary<string, Player>(或可能是<int, Player>)。

完成后,您可以从字典中创建Players类。

答案 1 :(得分:3)

你可以改用它。

"players": [
        {
            "id": 0,
            "success": 1,               
            "name": "xsusususdd"
        },
        {
            "id": 1,              
            "success": 1,               
            "name": "bleeps"
        },
        {
            "id": n,
            "success": x,
            "name": y
        }
    ]

这将创建一个包含personobjects的列表,您可以将其转换为字典

Dictionary<string, Player> dictionary = players.ToDictionary(v => v.id, v => v);

或只是List<Person>或您喜欢的内容。

如果您需要通过javascript访问它们,请使用例如players[1].name