[c#] Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

I have this JSON:

[
    {
        "Attributes": [
            {
                "Key": "Name",
                "Value": {
                    "Value": "Acc 1",
                    "Values": [
                        "Acc 1"
                    ]
                }
            },
            {
                "Key": "Id",
                "Value": {
                    "Value": "1",
                    "Values": [
                        "1"
                    ]
                }
            }
        ],
        "Name": "account",
        "Id": "1"
    },
    {
        "Attributes": [
            {
                "Key": "Name",
                "Value": {
                    "Value": "Acc 2",
                    "Values": [
                        "Acc 2"
                    ]
                }
            },
            {
                "Key": "Id",
                "Value": {
                    "Value": "2",
                    "Values": [
                        "2"
                    ]
                }
            }
        ],
        "Name": "account",
        "Id": "2"
    },
    {
        "Attributes": [
            {
                "Key": "Name",
                "Value": {
                    "Value": "Acc 3",
                    "Values": [
                        "Acc 3"
                    ]
                }
            },
            {
                "Key": "Id",
                "Value": {
                    "Value": "3",
                    "Values": [
                        "3"
                    ]
                }
            }
        ],
        "Name": "account",
        "Id": "2"
    }
]

And I have these classes:

public class RetrieveMultipleResponse
{
    public List<Attribute> Attributes { get; set; }
    public string Name { get; set; }
    public string Id { get; set; }
}

public class Value
{
    [JsonProperty("Value")]
    public string value { get; set; }
    public List<string> Values { get; set; }
}

public class Attribute
{
    public string Key { get; set; }
    public Value Value { get; set; }
}

I am trying to deserialize the above JSON using the code below:

var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);

but I am getting this error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'test.Model.RetrieveMultipleResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.

This question is related to c# arrays json serialization json.net

The answer is


Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object


If one wants to support Generics (in an extension method) this is the pattern...

public  static List<T> Deserialize<T>(this string SerializedJSONString)
{
    var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
    return stuff;
}

It is used like this:

var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();

MyClassType looks like this (must match name value pairs of JSON array)

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
 public class MyClassType
 {
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "Manager")]
    public string Manager { get; set; }

    [JsonProperty(PropertyName = "LastUpdate")]
    public DateTime LastUpdate { get; set; }
 }

Use NUGET to download Newtonsoft.Json add a reference where needed...

using Newtonsoft.Json;

var objResponse1 = 
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);

worked!


Use this, FrontData is JSON string:

var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);  

and extract list:

var a = objResponse1[0];
var b = a.CustomerData;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to serialization

laravel Unable to prepare route ... for serialization. Uses Closure TypeError: Object of type 'bytes' is not JSON serializable Best way to save a trained model in PyTorch? Convert Dictionary to JSON in Swift Java: JSON -> Protobuf & back conversion Understanding passport serialize deserialize How to generate serial version UID in Intellij Parcelable encountered IOException writing serializable object getactivity() Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Examples related to json.net

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path Return JsonResult from web api without its properties Checking for empty or null JToken in a JObject Send JSON via POST in C# and Receive the JSON returned? Unexpected character encountered while parsing value JSON.net: how to deserialize without using the default constructor? Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' Convert Json String to C# Object List