简体   繁体   中英

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 (eg {\\"name\\":\\"value\\"}) into type 'System.Collections.Generic.List`1 because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.\\r\\nTo fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM