【问题标题】:Deserialize JSON String with multiple possible object name in one class在一个类中反序列化具有多个可能对象名称的 JSON 字符串
【发布时间】:2014-05-06 22:38:15
【问题描述】:

我正在从一个游戏中向 3 个不同的用户发出服务器请求。

结果我得到了这个 JSON 字符串:

{
   "d4r1o": {
      "id": 1040806,
      "name": "D4R1O",
      "profileIconId": 596,
      "revisionDate": 1399366400000,
      "summonerLevel": 30
   },
   "snnovox": {
      "id": 65728,
      "name": "SN Novox",
      "profileIconId": 548,
      "revisionDate": 1399369344000,
      "summonerLevel": 30
   },
   "gmbecken": {
      "id": 421545,
      "name": "GM Becken",
      "profileIconId": 26,
      "revisionDate": 1399160360000,
      "summonerLevel": 30
   }
}

所以为了反序列化这个字符串,我有这些类

public class RootObject
{
    public SummonerDto d4r1o { get; set; }
    public SummonerDto snnovox { get; set; }
    public SummonerDto gmbecken { get; set; }
}

public class SummonerDto
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public long revisionDate { get; set; }
    public int summonerLevel { get; set; }
}

这很好用,但是如果用户想对自己的用户名提出请求怎么办,例如:snyucax

    {"snyucax": {
   "id": 48985,
   "name": "SN YucaX",
   "profileIconId": 504,
   "revisionDate": 1399257043000,
   "summonerLevel": 30
}}

有没有办法在 RootObject 类中只创建一个对象,让我可以使用任何用户名,而不必将该名称指定为对象?

【问题讨论】:

    标签: c# json class


    【解决方案1】:

    看起来您的数据更好地建模为字典。使用

    JsonConvert.DeserializeObject<Dictionary<string, SummonerDto>>(myJson)
    

    【讨论】:

      【解决方案2】:

      您应该为此使用字典。如果您使用的是 JSON.NET,则代码如下所示:

      var users = JsonConvert.DeserializeObject<Dictionary<string, SummonerDto>>(jsonDataString);
      

      然后你可以通过去获得用户:

      var user = users["d4r1o"];
      

      e: 好像Tim S 刚刚打败了我,哈哈。

      【讨论】:

      • 这很好用,实际上你的第二行帮助我理解了它,但现在我该怎么做才能列出我请求的所有用户?
      • 这个问题可以帮助您将字典转换为列表。 stackoverflow.com/questions/3968543/…
      【解决方案3】:

      我认为你不应该硬连线你的对象。而是使用字典或发送用户名并根据用户形成一个 json 对象并在客户端的浏览器或应用程序中反序列化它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-07
        • 2019-05-30
        • 2021-02-11
        • 2023-04-10
        • 2012-12-03
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        相关资源
        最近更新 更多