1

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.

1 Answer 1

2

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!

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

2 Comments

Works perfectly, Thanks alot!
Glad I could help! :)

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.