Mayamiko Mayamiko - 20 days ago 7
JSON Question

Error while parsing a JSON Response

I have this code below that gets a JSON response from an API call.

I have serialized it and I am trying to use Linq to Get a specific parent node and search through that node to find specific text.

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(some url).Result;
string strJson = response.Content.ReadAsStringAsync().Result;
object jObj = (JObject)JsonConvert.DeserializeObject(strJson);
Assert.IsTrue(response.IsSuccessStatusCode.Equals(true));
var a = JArray.Parse(jObj.ToString());
var Cast = a.SelectMany(x => x["episodes"]);


I Get an error:


Object is not Json Array


Any ideas of how I could do this?

Json response

{
"cast": [
{
"character": "Eddard Stark",
"credit_id": "5256c8ad19c2956ff60478a6",
"id": 48,
"name": "Sean Bean",
"profile_path": "/iIxP2IzvcLgr5WaTBD4UfSqaV3q.jpg",
"order": 0
},
{
"character": "Jon Snow",
"credit_id": "5256c8af19c2956ff6047af6",
"id": 239019,
"name": "Kit Harington",
"profile_path": "/dwRmvQUkddCx6Xi7vDrdnQL4SJ0.jpg",
"order": 0
}
],
"crew": [
{
"id": 93223,
"credit_id": "5256c8a219c2956ff6046f0b",
"name": "Brian Kirk",
"department": "Directing",
"job": "Director",
"profile_path": null
},
{
"id": 59984,
"credit_id": "54eef41d9251417971005b8d",
"name": "Marco Pontecorvo",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 1204180,
"credit_id": "54eef453c3a3680b80006153",
"name": "Frances Parker",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 9813,
"credit_id": "5256c8a019c2956ff6046e2b",
"name": "David Benioff",
"department": "Writing",
"job": "Writer",
"profile_path": "/8CuuNIKMzMUL1NKOPv9AqEwM7og.jpg"
},
{
"id": 228068,
"credit_id": "5256c8a219c2956ff6046e4b",
"name": "D. B. Weiss",
"department": "Writing",
"job": "Writer",
"profile_path": "/caUAtilEe06OwOjoQY3B7BgpARi.jpg"
}
]
}

Jim Jim
Answer

Try this:

JObject jObj = (JObject)JsonConvert.DeserializeObject(strJson);
Assert.IsTrue(response.IsSuccessStatusCode.Equals(true));
var a = (JArray)jObj["cast"];

instead of :

object jObj = (JObject)JsonConvert.DeserializeObject(strJson);
Assert.IsTrue(response.IsSuccessStatusCode.Equals(true));
var a = JArray.Parse(jObj.ToString());

It's already deserialized so no need to parse it anymore.

Acces the a array further, example:

foreach (var actor in a)
{
    Console.WriteLine(actor["character"]);
}

Alternatively you can use the dynamic functionality:

dynamic jObj = JsonConvert.DeserializeObject(strJson);
var a = jObj.cast;