c# - 在C#中,解析Json字符串

假设我有以下Json字符串


[


 {


"AppName": {


"Description":"Lorem ipsum dolor sit amet",


"Value":"1"


 },


"AnotherAppName": {


"Description":"consectetur adipisicing elit",


"Value":"String"


 },


"ThirdAppName": {


"Description":"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua",


"Value":"Text"


 },


"Application": {


"Description":"Ut enim ad minim veniam",


"Value":"100"


 },


"LastAppName": {


"Description":"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat",


"Value":"ZZZ"


 }


 }


]



我想将它解析为一个arraylist或字典,使用如下格式,


descriptionList["AppName"] ="Lorem ipsum dolor sit amet";


valueList["AppName"] ="1";



我一直在玩Json.Net,但是,我看到的例子并不明确我应该如何做到这一点,什么是最好的实现方法? 能不能像用jQuery那样做,使用foreach语句?

时间:

我在我的项目中使用Json.net,效果很好。在你的情况下,可以执行这个操作来解析你的json :

编辑:我修改了代码它支持读取json文件(数组)

要解析的代码:


void Main()


{


 var json = System.IO.File.ReadAllText(@"d:test.json");



 var objects = JArray.Parse(json); // parse as array 


 foreach(JObject root in objects)


 {


 foreach(KeyValuePair<String, JToken> app in root)


 {


 var appName = app.Key;


 var description = (String)app.Value["Description"];


 var value = (String)app.Value["Value"];



 Console.WriteLine(appName);


 Console.WriteLine(description);


 Console.WriteLine(value);


 Console.WriteLine("n");


 }


 }


}



输出:


AppName


Lorem ipsum dolor sit amet


1



AnotherAppName


consectetur adipisicing elit


String



ThirdAppName


sed do eiusmod tempor incididunt ut labore et dolore magna aliqua


Text



Application


Ut enim ad minim veniam


100



LastAppName


quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat


ZZZ



此外,你可以使用linqPad来测试代码,比在Visual Studio中创建解决方案或项目更容易。


json:


[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]



C#代码:只取一个值,例如"bike"


//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]



 dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);


 string Text = stuff1[0].hws[2];


 Console.WriteLine(Text);



输出:

 
bike



 

你可以试试 System.Web.Script.Serialization.JavaScriptSerializer


var json = new JavaScriptSerializer();


var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);



...