mabiyan
mabiyan

Reputation: 714

Handling Single and Multiple Json data

I have json string output as below, this is single item, there can be multiple of items as well.

[{"name":"someName","id":10,"state":"someState"}]

when i try to deserialize above json string using JsonConvert i get below error.

Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1 because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.

Here is code block,

string response = response.Content.ReadAsStringAsync().Result; // gives json string var result1 = JsonConvert.DeserializeObject<RootObject>(response); // this works var result2 = JsonConvert.DeserializeObject<List<RootObject>>(response); // gets error here

since json string can have single or multiple items, i cant use RootObject while deserializing.

RootObject class looks like

public class RootObject
{
    [JsonProperty("name")]
    public string Name{ get; set; }

    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("state")]
    public string State { get; set; }
}

I have tried using custom JsonConverter at property level and class level of RootObject class, referred this , but couldn't figure out how to use same in my case, appreciate if anyone could help me here.

Upvotes: 0

Views: 821

Answers (1)

A_Sk
A_Sk

Reputation: 4630

I am not sure, why you are saying the code is not working and it's throwing error. I tried to regenerate the issue but it seems to be working fine form me.

using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;


    public class Program
    {
        public static void Main()
        {
            string json="[{\"name\":\"someName\",\"id\":10,\"state\":\"someState\"},{\"name\":\"someName\",\"id\":10,\"state\":\"someState\"}]";
            string json2="[{\"name\":\"someName\",\"id\":10,\"state\":\"someState\"}]";
            var result1 = JsonConvert.DeserializeObject<List<RootObject>>(json);
            var result2 = JsonConvert.DeserializeObject<List<RootObject>>(json2);
            Console.WriteLine("result1 count="+result1.Count());
            Console.WriteLine("result2 count="+result2.Count());

        }



    }
    public class RootObject
    {
        [JsonProperty("name")]
        public string Name{ get; set; }

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("state")]
        public string State { get; set; }
    }

Dotnet Fiddle Here

Upvotes: 1

Related Questions