【问题标题】:How do deserialize this JSON into an object?如何将此 JSON 反序列化为对象?
【发布时间】:2011-11-23 21:41:42
【问题描述】:

我正在尝试使用 JSON.Net 将 JSON 对象反序列化为 C# 对象。

我要创建的对象是MonthlyPerformance,其中包含Type 列表,其中包含Categories 列表,而Categories 列表又包含Funds 列表。它们被定义为:

public class MonthlyPerformance
{
    public List<Type> Types { get; set; }
}

public class Type
{
    public int Id { get; set; }
    public string CountryId { get; set; }
    public string Name { get; set; }

    public List<Category> Categories { get; set; }

    public Type()
    {

    }
}

public class Category
{
    public int Id { get; set; }
    public string CountryId { get; set; }
    public string Name { get; set; }

    public List<ConfigurationFund> Funds { get; set; }

    public Category()
    {

    }
}

public class Fund
{
    public int Id { get; set; }
    public string CountryId { get; set; }
    public string Name { get; set; }

    public Fund()
    {

    }
}

我认为以下内容会做到这一点,但事实并非如此。它只是创建了一个 Type 对象的实例,所有内容都为空:

var file = File.ReadAllText(filePath);

var types = JsonConvert.DeserializeObject<Type>(file);

这是我正在使用的 JSON:

{
  "MonthlyPerformance": {
    "Type": [
      {
        "id": "65",
        "countryId": "IE",
        "name": "Irish Domestic Funds (Gross)",
        "Category": [
          {
            "id": "25003334",
            "countryId": "IE",
            "name": "UK Equity",
            "ConfigurationFund": [
              {
                "id": "25000301",
                "countryId": "IE",
                "name": "Aviva Irl UK Equity Fund"
              },
              {
                "id": "25000349",
                "countryId": "IE",
                "name": "New Ireland UK Equity 9"
              }
            ]
          },
          {
            "id": "25003339",
            "countryId": "IE",
            "name": "Irish Equity",
            "Fund": [
              {
                "id": "25000279",
                "countryId": "IE",
                "name": "Friends First Irish Equity G"
              },
              {
                "id": "25000305",
                "countryId": "IE",
                "name": "Irish Life Celticscope 2 G"
              }
            ]
          }
        ]
      },
      {
        "id": "80",
        "countryId": "IE",
        "name": "Irish Individual Pensions",
        "Category": [
          {
            "id": "25003347",
            "countryId": "IE",
            "name": "Asia Pacific Ex-Japan Equity",
            "Fund": [
              {
                "id": "25001789",
                "countryId": "IE",
                "name": "Aviva Irl Pacific Basin Eq"
              },
              {
                "id": "25002260",
                "countryId": "IE",
                "name": "Ir Life Pacific Eq Indexed  P"
              }
            ]
          },
          {
            "id": "25003365",
            "countryId": "IE",
            "name": "Flexible Equity",
            "Fund": [
              {
                "id": "25003238",
                "countryId": "IE",
                "name": "Friends First Protected Equity Plus Fund S2"
              },
              {
                "id": "25003267",
                "countryId": "IE",
                "name": "Friends First Protected Equity Plus Bond G"
              }
            ]
          }
        ]
      }
    ]
  }
}

我需要做什么才能让它工作?

编辑为包含MonthlyPerformance

【问题讨论】:

  • 你认为你的代码是指你定义的类型还是.net中预定义的Type。也看看james.newtonking.com/projects/json-net.aspx
  • 嗨@DarthVader,我可以看到Type 的类型在我自己的命名空间中。即使我将其更改为尝试创建MonthlyPerformance 的实例(我已经用这个更新了问题),它的行为仍然相同。

标签: c# json json.net deserialization


【解决方案1】:

我认为问题出在您的 Json 字符串中。

"Type": [ ... ] 

应该是

"Types": [ ... ]  

Types 是应该反序列化的属性的名称,您错误地Type 改为类名。

Type 类中的 Categories 属性也是如此。

另外我只是从 Json 字符串中删除了 "MonthlyPerformance" 根,它就像一个魅力。当然是使用 Json.NET。

这是修改后的 Json 的 sn-ps,具有适当的属性名称(通知、类型、类别、资金和缺少 MonthlyPerformance 根)

{
    "Types": [ 
    { 
    "id": "65", 
    "countryId": "IE", 
    "name": "Irish Domestic Funds (Gross)", 
    "Categories": [ 
        { 
        "id": "25003334", 
        "countryId": "IE", 
        "name": "UK Equity", 
        "Funds": [ 
            { 
            "id": "25000301", 
            "countryId": "IE", 
            "name": "Aviva Irl UK Equity Fund" 
            }, 
            { 
            "id": "25000349", 
            "countryId": "IE", 
            "name": "New Ireland UK Equity 9" 
        } 
    ] 
}

【讨论】:

    【解决方案2】:

    上面的类代码乍一看是正确的。

    我已经成功使用以下类 (JavaScriptSerializer) 反序列化 JSON。如下使用

    using System.Web.Script.Serialization;
    
    JavaScriptSerializer js = new JavaScriptSerializer();
    string file = File.ReadAllText(filePath);
    MonthyPerformance json = js.Deserialize<MonthlyPerformance>(file);
    

    哦,将 [Serializable] 添加到每个类的类属性中

    [Serializable]
    class whatever{}
    

    【讨论】:

      【解决方案3】:

      您会考虑使用dynamic 对象而不是反序列化为对象吗? (不声明MonthlyPerformanceTypeCategoryFund

      Facebook C# SDK get user language/region

      Google Maps v3 geocoding server-side

      用法:

      dynamic jobj = JsonUtils.JsonObject.GetDynamicJsonObject(JsonString);
      foreach (var item in jobj.MonthlyPerformance.Type)
      {
          Console.WriteLine(item.name);
          foreach (var category in item.Category)
          {
              Console.WriteLine("\t" + category.name);
              if (category.ConfigurationFund != null)
              {
                  foreach (var fund in category.ConfigurationFund)
                  {
                      Console.WriteLine("\t\t" + fund.name);
                  }
              }
          }
      }
      

      需要的助手类是here

      【讨论】:

        【解决方案4】:

        您的属性名称与 JSON 的名称不匹配。我希望序列化失败。

        鉴于您发布的 JSON,我希望您的 c# 类看起来像这样。我不熟悉 JSON.net,但我假设他们有一个属性装饰器,可以让您指定 c# 属性匹配的 JSON 属性的名称。

        public class MonthlyPerformance
        {
            public List<Type> Type { get; set; }
        }
        
        public class Type
        {
            public int id { get; set; }
            public string countryId { get; set; }
            public string Name { get; set; }
        
            public List<Category> Category { get; set; }
        
            public Type()
            {
        
            }
        }
        
        public class Category
        {
            public int id { get; set; }
            public string countryId { get; set; }
            public string name { get; set; }
        
            public List<Fund> ConfigurationFund{ get; set; }
        
            public Category()
            {
        
            }
        }
        
        public class Fund
        {
            public int id { get; set; }
            public string countryId { get; set; }
            public string name { get; set; }
        
            public Fund()
            {
        
            }
        }
        

        【讨论】:

          【解决方案5】:

          这是我用于 JSON 反序列化的...

          using System.Web.Script.Serialization;
          
          namespace blahblah
          {
              public partial class AccessTierService : ServiceBase
              {
                  public static T ia_deserialize_json<T>(string json_string)
                  {
                      try
                      {
                          if ((String.Compare(json_string, null) == 0) ||
                              (String.Compare(json_string, "") == 0) ||
                              (String.Compare(json_string, String.Empty) == 0))
                          {
                              return default(T);
                          }
                          JavaScriptSerializer serializer = new JavaScriptSerializer();
                          return (T)serializer.Deserialize<T>(json_string);
                      }
                      catch (Exception)
                      {
                          return default(T);
                      }
                  }
              }
          }
          

          并称它为...

          login_request = ia_deserialize_json<ol_login_request>(body_string);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多