wpf 在 C# 中将 JSON 字符串解析为 JSON 对象,而无需编写额外的对象类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24788850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse JSON string to a JSON Object in C# without writing extra object classes
提问by KField
I'm new to C# and I am building a WPF app. Right now I trying to figure out how I can parse a JSON string like this:
我是 C# 新手,正在构建 WPF 应用程序。现在我想弄清楚如何解析这样的 JSON 字符串:
{
"Name": "Apple",
"ExpiryDate": "2008-12-28T00:00:00","Price": 3.99,
"Sizes": ["Small","Medium","Large"]
}
into a JSON Object magically.
神奇地变成一个 JSON 对象。
I did some search online and all the solutions requires writing an object class that has the same structure as the JSON string. The string above is just an example and the actually JSON response is much more complicated, so I don't want to write a huge class for it.
我在网上做了一些搜索,所有的解决方案都需要编写一个与 JSON 字符串具有相同结构的对象类。上面的字符串只是一个例子,实际的 JSON 响应要复杂得多,所以我不想为它编写一个巨大的类。
Is there a library that allows me to do something similar to these:
是否有一个库可以让我做类似的事情:
JsonObject jo = new JsonObject(JsonString);
string name = jo["Name"]; // And the name would have "Apple" as its value
回答by Tim S.
I'd recommend you use Json.NETas your JSON library. The following code creates a dynamicobject that you can work with. magicis actually an instance of JObjectin your example, by the way.
我建议您使用Json.NET作为您的 JSON 库。以下代码创建了一个dynamic您可以使用的对象。顺便说一下,magic实际上是JObject您示例中的一个实例。
dynamic magic = JsonConvert.DeserializeObject(jsonStr);
string name1 = magic.Name; // "Apple"
string name2 = magic["Name"]; // "Apple"

