How do deserialize this JSON into an object?

徘徊边缘 提交于 2019-12-19 09:09:42

问题


I'm trying to use JSON.Net to deserialize a JSON object into a C# object.

The object I want to create is MonthlyPerformance which contains a list of Type, which contains a list of Categories, which in turn contains a list of Funds. They are defined as:

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()
    {

    }
}

I thought the following would do it, but it's not. It's just creating an instance of the Type object with everything null:

var file = File.ReadAllText(filePath);

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

This is the JSON that I'm using:

{
  "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"
              }
            ]
          }
        ]
      }
    ]
  }
}

What do I need to do to get this to work?

edited to include MonthlyPerformance


回答1:


I believe the problem is in your Json string.

"Type": [ ... ] 

Should be

"Types": [ ... ]  

Types is the name of property that should be deserialized, you mistakenly put Type the class name instead.

The same goes for Categories property in the Type class.

Also I simply removed "MonthlyPerformance" root from the Json string and it worked like a charm. With Json.NET of course.

Here is a snippets of the modified Json with appropriate property names (notice, Types, Categories, Funds and the absence of MonthlyPerformance root)

{
    "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:


the above code that you have for your classes looks correct on first glance.

i've been successful with deserializing JSON with the following class(JavaScriptSerializer). used as follows

using System.Web.Script.Serialization;

JavaScriptSerializer js = new JavaScriptSerializer();
string file = File.ReadAllText(filePath);
MonthyPerformance json = js.Deserialize<MonthlyPerformance>(file);

oh, and add [Serializable] to your class attributes for each class

[Serializable]
class whatever{}



回答3:


Would you think to use dynamic object instead of deserializing to an object? (without declaring MonthlyPerformance, Type, Category, Fund)

Facebook C# SDK get user language/region

Google Maps v3 geocoding server-side

Usage:

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);
            }
        }
    }
}

Helper class needed is here




回答4:


Your property names do not match that of your JSON. I would expect the serialization to fail.

Given the JSON you posted I would expect your c# classes to look like this. I'm not familiar with JSON.net but I would assume they have a property decorator that would allow you to specify the name of the JSON property the c# prop matches too.

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:


This is what I use for JSON deserialization...

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);
            }
        }
    }
}

and to call it...

login_request = ia_deserialize_json<ol_login_request>(body_string);


来源:https://stackoverflow.com/questions/8249454/how-do-deserialize-this-json-into-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!