1

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

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

我正在使用的第 3 方 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);
4

2 回答 2

3

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

一旦你有了它,你就可以Players从你的字典中创建一个类。

于 2012-12-06T12:16:56.000 回答
3

你可以改用这个。

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

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

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

或者只是一个List<Person>或你喜欢的。

如果您需要从 javascript 访问它们,只需使用 eg players[1].name

于 2012-12-06T12:27:03.290 回答