将 JSON 反序列化为对象 [英] Deserializing JSON into an object

查看:66
本文介绍了将 JSON 反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 JSON:

{
    "foo" : [ 
        { "bar" : "baz" },
        { "bar" : "qux" }
    ]
}

我想将其反序列化为一个集合.我已经定义了这个类:

And I want to deserialize this into a collection. I have defined this class:

public class Foo
{
    public string bar { get; set; }
}

但是,以下代码不起作用:

However, the following code does not work:

 JsonConvert.DeserializeObject<List<Foo>>(jsonString);

如何反序列化我的 JSON?

How can I deserialize my JSON?

推荐答案

那个 JSON 不是 Foo JSON 数组.代码 JsonConvert.DeserializeObject(jsonString) 将解析 JSON 字符串从根开始,您的类型 T 必须匹配JSON 结构完全正确.解析器不会猜测哪个 JSON 成员应该代表您正在寻找的 List.

That JSON is not a Foo JSON array. The code JsonConvert.DeserializeObject<T>(jsonString) will parse the JSON string from the root on up, and your type T must match that JSON structure exactly. The parser is not going to guess which JSON member is supposed to represent the List<Foo> you're looking for.

您需要一个根对象,它表示来自根元素的 JSON.

You need a root object, that represents the JSON from the root element.

您可以轻松地让类从示例 JSON 中生成.为此,请复制您的 JSON 并单击 Edit ->粘贴特殊 ->在 Visual Studio 中将 JSON 粘贴为类.

You can easily let the classes to do that be generated from a sample JSON. To do this, copy your JSON and click Edit -> Paste Special -> Paste JSON As Classes in Visual Studio.

或者,您可以在 http://json2csharp.com 上执行相同的操作,这会生成或多或少相同的类.

Alternatively, you could do the same on http://json2csharp.com, which generates more or less the same classes.

您会看到该集合实际上比预期更深一个元素:

You'll see that the collection actually is one element deeper than expected:

public class Foo
{
    public string bar { get; set; }
}

public class RootObject
{
    public List<Foo> foo { get; set; }
}

现在您可以从根反序列化 JSON(并确保将 RootObject 重命名为有用的名称):

Now you can deserialize the JSON from the root (and be sure to rename RootObject to something useful):

var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

并访问集合:

foreach (var foo in rootObject.foo)
{
    // foo is a `Foo`

}

您始终可以重命名属性以遵循您的大小写约定并将 JsonProperty 属性应用于它们:

You can always rename properties to follow your casing convention and apply a JsonProperty attribute to them:

public class Foo
{
    [JsonProperty("bar")]
    public string Bar { get; set; }
}

还要确保 JSON 包含足够的示例数据.类解析器必须根据在 JSON 中找到的内容来猜测适当的 C# 类型.

Also make sure that the JSON contains enough sample data. The class parser will have to guess the appropriate C# type based on the contents found in the JSON.

这篇关于将 JSON 反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆