简体   繁体   English

将 JSON 反序列化为字典<string, List<string> &gt;

[英]Deserialize JSON to Dictionary<string, List<string>>

I am very new to JSON, so I may have missed something.我对 JSON 很陌生,所以我可能错过了一些东西。 But here's what I am attempting.但这是我正在尝试的。 I want to Deserialize the following type of JSON我想反序列化以下类型的 JSON

{
  "Size": 
  {
    "Creature": 
    {
      "Dragon": 
      [
        "Huge",
        "Colossal",
        "Mountain-sized"
      ],

      "Wolf": 
      [
        "Pup",
        "Fully grown",
        "Giant"
      ]
    },

    "Building": 
    [
      "Small",
      "Medium",
      "Large"
    ]
  }
}

The core function of the JSON is intended so that I am not sure how nested it may become over time. JSON 的核心功能旨在使我不确定随着时间的推移它可能会如何嵌套。 With creature having subtypes depending on what kind of creature it is, and same for building and so on.生物具有子类型取决于它是什么类型的生物,建筑等也是如此。

I've attempted with this code我已经尝试过使用此代码

using StreamReader r = new StreamReader("Storage.json");
string json = r.ReadToEnd();
CoreStorageDict = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);

I would like to Deserialize it into a dictionary as directly as possible, but I've yet to find a good way to do it and I think I am missing something fundamental about the whole system.我想尽可能直接地将它反序列化为字典,但我还没有找到一个好的方法,我认为我缺少关于整个系统的一些基本知识。

Is the JSON wrong or is my code wrong?是 JSON 错误还是我的代码错误? Or both perhaps?或者两者都有?

If you define the following classes:如果定义以下类:

public class Creature
{
    public IList<string> Dragon { get; set; }
    public IList<string> Wolf { get; set; }
}

public class Size
{
    public Creature Creature { get; set; }
    public IList<string> Building { get; set; }
}

public class Example
{
    public Size Size { get; set; }
}

and then try to deserialize your json you will make it.然后尝试反序列化您的 json,您将成功。 You can alter the name of classes as you want.您可以根据需要更改类的名称。 For the names above you have just to do this:对于上面的名称,您只需执行以下操作:

var result = JsonConvert.DeserializeObject<Example>(json);

What is the problem with the approach you followed ?你采用的方法有什么问题?

The problem is that you have nested types.问题是您有嵌套类型。 So you have to declare each and any type properly in order the deserialization work.因此,您必须正确声明每种类型,以便反序列化工作。

How you can find which classes are needed to be declared ?如何找到需要声明哪些类?

There are may tools out there that do this job.可能有一些工具可以完成这项工作。 The one I used is the following one JSON Utils .我使用的是以下JSON Utils Provided that you have a valid json, these tools can auto generate the required classes.只要您有一个有效的 json,这些工具就可以自动生成所需的类。 If I am correct, also Visual Studio, provides you with such a functionality.如果我是对的,Visual Studio 也为您提供了这样的功能。

Making classes is definitely a good way to do it and I agree with Christos.上课绝对是一个很好的方法,我同意克里斯托斯的观点。

However if you're doing a one-time thing and don't want to bother making classes you can hack it by deserializing the whole thing to dynamic and then re-serializing and deserializing the part you need, to your expected type, like this.但是,如果您正在做一次性的事情并且不想打扰制作课程,您可以通过将整个事情反序列化为动态然后将您需要的部分重新序列化和反序列化为您期望的类型来破解它,就像这样.

   var json = @"{
                    ""Size"": {
                      ""Creature"": {
                        ""Dragon"": [
                          ""Huge"",
                          ""Colossal"",
                          ""Mountain-sized""
                        ],
                        ""Wolf"": [
                          ""Pup"",
                          ""Fully grown"",
                          ""Giant""
                        ]
                      },
                      ""Building"": [
                        ""Small"",
                        ""Medium"",
                        ""Large""
                      ]
                    }
                  }";

            var deserialized = JsonConvert.DeserializeObject<dynamic>(json);

            var thePartYouWant = deserialized.Size.Creature;

            var dict = (Dictionary<string, List<string>>) JsonConvert
                .DeserializeObject<Dictionary<string, List<string>>>(
                    (JsonConvert.SerializeObject(thePartYouWant)));

            dict.Keys.ToList().ForEach(Console.WriteLine);

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

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