How can I get individual values from this JSON? For example the SSN? Also, some items are arrays that can hold multiples (addresses, phones). What is the best way to parse this? I have tried with JArray.Parse(data), but still can't "find" the individual items. Can anyone point me in the right direction?
[{
"firstName": "test",
"middleName": "test",
"lastName": "test"
},
{
"addresses":
[{
"street": "test",
"city": "test",
"state": "test",
"zip": "test"
}]
},
{
"DOB": ""
},
{
"SSN": "123123123"
},
{
"occupation": "test",
"typeOfOccupation": "test"
},
{
"phones":
[{
"phone": "",
"type": ""
}]
},
{
"Email": ""
},
{
"typeOfId": "",
"idNumber": "",
"expirationDate": ""
}]
-
5Show your actual code. Parsing JSON in c# is a topic covered repeatedly and extensively.tnw– tnw2017年03月21日 18:10:59 +00:00Commented Mar 21, 2017 at 18:10
-
This could be helpful. stackoverflow.com/questions/16079116/…SWPhantom– SWPhantom2017年03月21日 18:17:30 +00:00Commented Mar 21, 2017 at 18:17
1 Answer 1
You said you used JArray.Parse
but are you using it as a dynamic
? Check Query JSON with dynamic with JSON.Net.
var json = "[{ \"firstName\": \"test\", \"middleName\": \"test\", \"lastName\": \"test\" }, { \"addresses\": [{ \"street\": \"test\", \"city\": \"test\", \"state\": \"test\", \"zip\": \"test\" }] }, { \"DOB\": \"\" }, { \"SSN\": \"123123123\" }, { \"occupation\": \"test\", \"typeOfOccupation\": \"test\" }, { \"phones\": [{ \"phone\": \"\", \"type\": \"\" }] }, { \"Email\": \"\" }, { \"typeOfId\": \"\", \"idNumber\": \"\", \"expirationDate\": \"\" }]";
var data = JArray.Parse(json);
JToken ssn = data.SelectToken("$..SSN")
if(ssn!=null){
Console.WriteLine(ssn.Value<string>());
}
Working fiddle here.
answered Mar 21, 2017 at 18:19
-
Thank you Matias. Is there any way to do this without knowing the position of the data? for example, sometimes the SSN might appear before the DOB (or there may be some other change to the structure)? Can I "find" the SSN anyways?fredjo– fredjo2017年03月21日 19:06:55 +00:00Commented Mar 21, 2017 at 19:06
-
Since it's an Array and not an Object, no, don't think you can unless you loop in the entire array looking for said attribute, not really efficient.Matias Quaranta– Matias Quaranta2017年03月21日 19:22:33 +00:00Commented Mar 21, 2017 at 19:22
-
this seems to work: dynamic arr = JArray.Parse(data); JToken ssn = arr.SelectToken("$..SSN"); do you see any problem with it?fredjo– fredjo2017年03月21日 19:28:31 +00:00Commented Mar 21, 2017 at 19:28
-
Interesting, never tried the dots on the SelectToken method, updated the fiddle with the working code using
Value<string>()
Matias Quaranta– Matias Quaranta2017年03月21日 19:54:39 +00:00Commented Mar 21, 2017 at 19:54
lang-cs