【问题标题】:Deserialize JSON with numbers as property names使用数字作为属性名称反序列化 JSON
【发布时间】:2017-04-12 21:41:44
【问题描述】:

我有这样的 JSON:

{"rows":
    {
        "1":{"rowNumber":1,"productID":"100"},
        "2":{"rowNumber":2,"productID":"101"},
        "3":{"rowNumber":3,"productID":"102"}
    }
}

我需要建立领域模型。

例如:

class Row 
{
    public int rowNumber{get; set;}
    public string productID{get; set;}
}

根对象

class RootObject
{
   public ? ? rows {get; set;}
}

什么样的类型必须是 rows 属性?

【问题讨论】:

标签: c# json


【解决方案1】:

答案是

public Dictionary<int, Row> rows { get; set; }

并使用

JsonConvert.DeserializeObject<RootObject>(json);

用于反序列化。 JsonConvert 来自Newtonsoft 库。

【讨论】:

    【解决方案2】:

    似乎您正在寻找 int 类型或 int32 类型:

    //Assumes you are using Newtonsoft JSON Nuget Package
    
    List<int> products = null;
    
    products = JsonConvert.DeserializeObject<List<int>>(json);
    

    应该可以 - 但是您在 StackOverflow 上找到的所有代码都应该被视为伪代码。这至少应该为您指明正确的方向。希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      您的问题不清楚,但这可能很有用

      public class Account
      {
          public string Email { get; set; }
          public bool Active { get; set; }
          public DateTime CreatedDate { get; set; }
          public IList<string> Roles { get; set; }
      };
      string json = @"{
         'Email': 'james@example.com',
         'Active': true,
         'CreatedDate': '2013-01-20T00:00:00Z',
        'Roles': [
           'User',
           'Admin'
         ]
       }";
      
      Account account = JsonConvert.DeserializeObject<Account>(json);
      
      Console.WriteLine(account.Email);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 2016-01-14
        • 2021-12-10
        相关资源
        最近更新 更多