解析JSON字符串在C#中的JSON对象,而无需编写额外的对象类 [英] Parse JSON string to a JSON Object in C# without writing extra object classes

查看:409
本文介绍了解析JSON字符串在C#中的JSON对象,而无需编写额外的对象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#和我建立一个WPF应用程序。现在,我试图找出我怎么能分析一个JSON字符串是这样的:

  {
名称: 苹果,
ExpiryDate:2008-12-28T00:00:00,价格:3.99,
尺寸:小,中,大 ]
}

成JSON对象神奇。



我做了一些网上搜索,所有的解决方案需要编写具有相同的结构JSON字符串对象类。上面的字符串是只是一个例子,实际JSON响应要复杂得多,所以我不想为它编写一个巨大的类。



有一个图书馆允许我做类似的东西,这些:

 的JSONObject乔=新的JSONObject(JsonString); 
字符串名称=祚[名称]; //和名字将有苹果作为它的值


解决方案

我建议你使用 Json.NET 为您的JSON库。下面的代码创建一个动态对象,您可以一起工作。 魔术实际上是的一个实例 JObject 在你的榜样,顺便说一句。

 动态魔= JsonConvert.DeserializeObject(jsonStr); 
字符串名称1 = magic.Name; //苹果
字符串名称2 =魔法[名称]; //苹果


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:

{
   "Name": "Apple", 
   "ExpiryDate": "2008-12-28T00:00:00","Price": 3.99, 
   "Sizes": ["Small","Medium","Large"]
}

into a JSON Object magically.

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.

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

解决方案

I'd recommend you use Json.NET as your JSON library. The following code creates a dynamic object that you can work with. magic is actually an instance of JObject in your example, by the way.

dynamic magic = JsonConvert.DeserializeObject(jsonStr);
string name1 = magic.Name;    // "Apple"
string name2 = magic["Name"]; // "Apple"

这篇关于解析JSON字符串在C#中的JSON对象,而无需编写额外的对象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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