简体   繁体   English

如何使用Newtonsoft从我的JSON数组反序列化为其值是C#.NET中“资源”对象的字典数组?

[英]How to deserialize from my JSON array to an array of dictionaries whose values are my “Resource” objects in C# .NET using Newtonsoft?

I'm getting the following error when trying to deserliaze my JSON into a Dictionary<string, Resources>[] : 尝试将JSON反序列化为Dictionary<string, Resources>[]时出现以下错误:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll Newtonsoft.Json.dll中发生了类型为'Newtonsoft.Json.JsonSerializationException'的未处理异常

Additional information: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.Dictionary`2[System.String,MyProject.Resource][]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. 附加信息:无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.Dictionary`2 [System.String,MyProject.Resource] []',因为该类型需要JSON数组(例如[1,2,3])可正确反序列化。

To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型)数组或列表),可以从JSON对象反序列化。 JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。

My Program.Main(): 我的Program.Main():

    public class Program
            {
                public static void Main(string[] Args)
                {
                    var options = new Options()
                    {
                        Option1 = "foo",
                        Option2 = "bar",
                        Resources = JsonConvert.DeserializeObject<Dictionary<string, Resource>[]>(resources.json)
                    };
                }
            }

My resources.json: 我的resources.json:

{
    "global": [

        {
            "title": "global1",
            "url": "~/global1"
        },
        {
            "title": "global2",
            "url": "~/global2"
        }
    ],
    "ACC": [
        {
            "title": "acc1",
            "url": "~/acc1/"
        },
        {
            "title": "acc2",
            "url": "~/acc2/"
        }
    ],
    "ECC": [
        {
            "title": "ecc1",
            "url": "~/ecc1/"
        },
        {
            "title": "ecc2",
            "url": "~/ecc2/"
        }
    ],
    "ECB": [
        {
            "title": "ecb1",
            "url": "~/ecb1"
        }
    ]

}

My Resource class: 我的资源班:

public class Resource
    {
        public List<string> titles { get; set; }

        public List<string> urls { get; set; }
    }

My Options class: 我的选项类别:

public class Options
    {
        public string Option1 { get; set; }
        public string Option2 { get; set; }
        public Dictionary<string, Resource>[] Resources { get; set; }
    }

Your Json doesn't match up with your class structure. 您的Json与您的类结构不匹配。
If you want to keep your class structure your json has to look like this: 如果要保持类结构,则json必须如下所示:

{
   "global":{
      "titles":[
         "global1",
         "global2"
      ],
      "urls":[
         "~/global1",
         "~/global2"
      ]
   },
   "acc":{
      "titles":[
         "acc1",
         "acc2"
      ],
      "urls":[
         "~/acc1",
         "~/acc2"
      ]
   },

   ...    

}

If you can't influence your json file (for what ever reason) your class structure has to look like this: 如果您无法影响json文件(无论出于何种原因),您的类结构必须如下所示:

public class Rootobject
{
   public Global[] global { get; set; }
   public ACC[] ACC { get; set; }
   public ECC[] ECC { get; set; }
   public ECB[] ECB { get; set; }
}

public class Global
{
   public string title { get; set; }
   public string url { get; set; }
}

public class ACC
{
   public string title { get; set; }
   public string url { get; set; }
}

public class ECC
{
   public string title { get; set; }
   public string url { get; set; }
}

public class ECB
{
   public string title { get; set; }
   public string url { get; set; }
}

Then you can deserialize it like this: 然后,您可以像这样反序列化它:

Resources = JsonConvert.DeserializeObject<Rootobject>(resources.json)

Little note for the next time: 下次需要注意的一点:
If you are not sure how your class structure has to look like (regarding to a json string), you can copy the json string and go to: 如果不确定类结构的样子(关于json字符串),则可以复制json字符串并转到:

Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes Visual Studio->编辑->选择性粘贴->将JSON作为类粘贴

and Visual Studio will make up the appropriate class structure. Visual Studio将组成适当的类结构。

Your JSON does not represent an array of dictionaries ( Dictionary<string, Resource>[] ), it represents a dictionary of arrays ( Dictionary<string, Resource[]> ). 您的JSON不代表字典的数组( Dictionary<string, Resource>[] ),而是代表数组的字典( Dictionary<string, Resource[]> )。 That is why you are getting the error. 这就是为什么您得到错误。

Also, your Resource class needs to be defined like this to match the JSON: 另外,您的Resource类需要像这样定义以匹配JSON:

public class Resource
{
    public string Title { get; set; }
    public string Url { get; set; }
}

You can then deserialize like this: 然后,您可以像这样反序列化:

 Resources = JsonConvert.DeserializeObject<Dictionary<string, Resource[]>>(resources.json)

See fiddle here: https://dotnetfiddle.net/8s2eQd 在这里查看小提琴: https//dotnetfiddle.net/8s2eQd

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

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