0

Here is the list of data I receive, property names are can be different;

{"data":"[
    {   
        "id":"1",
        "name":"aa",
        "email":"[email protected]",
        "address":"11"
    },
    {   
        "id":"2",
        "name":"bb",
        "email":"[email protected]",
        "address":"22"
    }
]"}

Here is my c# code

Which I get an error on the 3rd line. Unable to read json data. Check the url you typed.Invalid cast from 'System.String' to 'Newtonsoft.Json.Linq.JObject'.

 var jsonStr = wc.DownloadString(url);
 JToken outer = JToken.Parse(jsonStr);
 JObject inner = outer["data"].Value<JObject>();

 List<string> keys = inner.Properties().Select(p => p.Name).ToList();

How can my output be like this;

id
name
emal
address

It would be great if I also consider n level array such as address > street and address > postcode

Many thanks.

1 Answer 1

6
var jObj = JObject.Parse(json);
var props = jObj["data"][0].Select(x => ((JProperty)x).Name).ToList();

BTW: your json is not correct, it should be something like this

{data:[
 { "id":"1", 
        "name":"aa",
        "email":"[email protected]",
        "address":"11"
    },
    {"id":"2",
        "name":"bb",
        "email":"[email protected]",
        "address":"22"
    }
]}

See the " after data: in your question

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

4 Comments

updated json string now, but instead of removing it I had to wrap it with " as how it comes from the end point.
@Cem It is still not a valid json. How to parse invalid jsons is out of scope of this question and i don't know how it can be done easily.
@Cem See {"data":"[...]"}. Is it an array of objects or a single string? In this form it is neither.
Sorry I was passing string instead of object hence the ", now it works fine. thanks a lot.

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.