简体   繁体   English

如何将此JSON反序列化为对象?

[英]How do deserialize this JSON into an object?

I'm trying to use JSON.Net to deserialize a JSON object into a C# object. 我正在尝试使用JSON.Net将JSON对象反序列化为C#对象。

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 . 我想要创建的对象是MonthlyPerformance ,它包含Type列表,其中包含Categories列表,而MonthlyPerformance列表又包含一个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: 它只是创建一个Type对象的实例,其中包含所有null:

var file = File.ReadAllText(filePath);

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

This is the JSON that I'm using: 这是我正在使用的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"
              }
            ]
          }
        ]
      }
    ]
  }
}

What do I need to do to get this to work? 我需要做些什么才能让它发挥作用?

edited to include MonthlyPerformance 编辑以包含MonthlyPerformance

Would you think to use dynamic object instead of deserializing to an object? 您是否会考虑使用dynamic对象而不是反序列化到对象? (without declaring MonthlyPerformance , Type , Category , Fund ) (未声明MonthlyPerformanceTypeCategoryFund

Facebook C# SDK get user language/region Facebook C#SDK获取用户语言/区域

Google Maps v3 geocoding server-side Google Maps v3地理编码服务器端

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 所需的助手类就在这里

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). 我已成功使用以下类(JavaScriptSerializer)反序列化JSON。 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]

[Serializable]
class whatever{}

I believe the problem is in your Json string. 我相信问题出在你的Json字符串中。

"Type": [ ... ] 

Should be 应该

"Types": [ ... ]  

Types is the name of property that should be deserialized, you mistakenly put Type the class name instead. Types是应该反序列化的属性的名称,您错误地Type命名为。

The same goes for Categories property in the Type class. Type类中的Categories属性也是如此。

Also I simply removed "MonthlyPerformance" root from the Json string and it worked like a charm. 此外,我只是从Json字符串中删除了"MonthlyPerformance"根,它就像一个魅力。 With Json.NET of course. 当然还有Json.NET。

Here is a snippets of the modified Json with appropriate property names (notice, Types, Categories, Funds and the absence of MonthlyPerformance root) 以下是修改过的Json的片段,其中包含适当的属性名称(通知,类型,类别,基金和缺少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" 
        } 
    ] 
}

Your property names do not match that of your JSON. 您的属性名称与JSON的属性名称不匹配。 I would expect the serialization to fail. 我希望序列化失败。

Given the JSON you posted I would expect your c# classes to look like this. 鉴于您发布的JSON,我希望您的c#类看起来像这样。 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. 我不熟悉JSON.net,但我认为他们有一个属性装饰器,允许你指定c#prop匹配的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()
    {

    }
}

This is what I use for JSON deserialization... 这就是我用于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);
            }
        }
    }
}

and to call it... 并称之为......

login_request = ia_deserialize_json<ol_login_request>(body_string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM