-6

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": ""
}]
2
  • 5
    Show your actual code. Parsing JSON in c# is a topic covered repeatedly and extensively. Commented Mar 21, 2017 at 18:10
  • This could be helpful. stackoverflow.com/questions/16079116/… Commented Mar 21, 2017 at 18:17

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
this seems to work: dynamic arr = JArray.Parse(data); JToken ssn = arr.SelectToken("$..SSN"); do you see any problem with it?
Interesting, never tried the dots on the SelectToken method, updated the fiddle with the working code using Value<string>()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.