JSON反序列化到一个对象 [英] Deserializing JSON into an object
问题描述
我有一些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; }
}
但是,下面的code不工作:
However, the following code does not work:
JsonConvert.DeserializeObject<List<Foo>>(jsonString);
我如何反序列化JSON我?
How can I deserialize my JSON?
推荐答案
这JSON是不是富
JSON阵列。在code JsonConvert.DeserializeObject&LT; T&GT;(jsonString)
将从根解析最多 JSON字符串,然后你键入 T
必须在JSON结构完全相同。解析器是不会去猜测的这的JSON成员应该重新present在列表&LT;富方式&gt;
你正在寻找
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.
您需要一个根对象时,重新$ P $从根元素psents的JSON。
You need a root object, that represents the JSON from the root element.
您可以轻松地让这从一个样本JSON生成的类的事。要做到这一点,复制您的JSON,然后点击编辑 - &GT;选择性粘贴 - &GT;粘贴JSON作为在Visual Studio中的类
。
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屋!