user3801447
user3801447

Reputation: 41

Parsing A JSON String with Multiple top-level items into multiple JSON Objects

I am dealing with a situation where i am retrieving JSON data from an API. I am then attempting to map this data to its corresponding JSON object definition (which is huge so i wont put it in here) and it all works great for a single top-level item. However, in a situation where the string i retrieve contains multiple top-level JSON items, i cannot parse the JSON data as it has not been split.

I cannot seem to figure out an effective way to split the string and then parse the objects.

Things i have tried include items from the following articles: Parse Json string in C# https://stackoverflow.com/questions/32273617/parse-json-string-into-liststringhttps://stackoverflow.com/questions/13721686/parse-this-json-string-to-string-array-c-sharp

And the code i am using the map the single item to a single object is as follows:

public void createTicketObj(string json_string)
    {

        //take in the json string containing the items & deserialize it.
        var item = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(json_string);
        //works for a single JSON item, however not for multiple records. 

    }

If someone could point me in the right direction that would be greatly appreciated! Thanks.

Upvotes: 1

Views: 3154

Answers (1)

mindOfAi
mindOfAi

Reputation: 4632

If you have multiple records, you should use put it in a List<T>. Try using this:

var item = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RootObject>>(json_string);

However, this won't work with a single item. In order to make it work, check the JSON if it is an single or a multiple record first using this:

var token = JToken.Parse(json_string);

if (token is JArray)
{
// Do something
}
else if (token is JObject)
{
// Do something
}

Hope it helps!

Upvotes: 2

Related Questions