How to search JSON string for fields?

耗尽温柔 提交于 2019-12-11 03:36:58

问题


I have a JSON string: [{"number":"123-456-789","array":["1", "2"]}]. I want check to see if this JSON contains a "number" field. What I am trying:

string jsonString = [{"number":"123-456-789","array":["1", "2"]}];
Newtonsoft.Json.Linq.JArray jsonObject = JArray.Parse(jsonString);

How do I then "search" this jsonObject for a specified field?


回答1:


If you would like to test if the "number" property exists, then you can use:

bool exists = jsonObject[0].Children<JProperty>().Any(p => p.Name == "number");

If you want to get the value of the "number" property, then you can use

string number = jsonObject[0]["number"].Value<string>();

Edit Here is how to get the "array" property

string[] arr = jsonObject[0]["array"].Values<string>().ToArray();



回答2:


Like this:

        var isThereNumber = jsonObject[0]["number"];
        var isThereNumber2 = jsonObject[0]["number2"];

Cheers



来源:https://stackoverflow.com/questions/24496816/how-to-search-json-string-for-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!