简体   繁体   English

在 C# 中反序列化 Json

[英]Deserialize Json in C#

{
  "person": "david",
  "images": {
    "usable_sizes": [
      [
        [150,
          41
        ],
        "image1.png"
      ],
      [
        [220,
          61
        ],
        "image2.png"
      ],
      [
        [220,
          61
        ],
        "image3.png"
      ]
    ],
    "uploader": null
  }
}

I am using a JavaScriptSerializer in C# to parse some JSON.我在 C# 中使用 JavaScriptSerializer 来解析一些 JSON。 The above is the string I get back from the webrequest.上面是我从 webrequest 中得到的字符串。 Calling Deserialize on the string puts the Person in the right place in the object, but I don't know what type to use for the array nested under "images."对字符串调用 Deserialize 会将 Person 放在对象中的正确位置,但我不知道嵌套在“图像”下的数组使用什么类型。 I am at a complete loss.我完全不知所措。

here is relevant code:这是相关代码:

TopLevelObject topObj = new JavaScriptSerialize().Deserialize<TopLevelObj>(jsonStream);

public TopLevelObject
{
    public string person;
    public imgStruct images;
}

public class imgStructure
{
    public List<string[,][]> available_sizes;
}

but that's not taking.但那不是拿。 I have tried a variety of other forms for the class, but can't get the deserialize to put the data in without proper keys.我已经为该类尝试了各种其他形式,但是如果没有正确的键,就无法进行反序列化以将数据放入。 I have no ability to change the inbound JSON as I am consuming it from a third party.我无法更改入站 JSON,因为我从第三方使用它。

This is what I believe your classes should look like:这就是我认为您的课程应该是这样的:

public class RootObj
{
    public string person;
    public ImageDataObj images;
}

public class ImageDataObj
{
    public object uploader;
    public List<List<object>> usable_sizes
}

As you can see the inner list is a list of objects.如您所见,内部列表是一个对象列表。 That is because the list has items of different types: one is a list (numerical data [150, 41]) and the other is a string (image name).这是因为列表具有不同类型的项目:一个是列表(数字数据 [150, 41]),另一个是字符串(图像名称)。 I do not think you can strongly type the inner list for that reason.由于这个原因,我认为您不能强烈输入内部列表。 Maybe it is worth examining on runtime (using the VS debugging tools) the structure of the objects inside the inner list and that could give you an indication of how to map it.也许值得在运行时(使用 VS 调试工具)检查内部列表中对象的结构,这可以为您提供如何映射它的指示。

How the usable_images property type does look like if you take it to its detail is:如果详细了解 usable_images 属性类型,它的样子是这样的:

public List<List<Dictionary<List<int>,string>>> usable_sizes

but that is just a guess.但这只是一个猜测。

我建议去JSON.org并使用他们预先构建的解决方案之一。

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

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