[c#] Cannot deserialize the current JSON array (e.g. [1,2,3])

I am trying to read my JSON result.

Here is my RootObject

public class RootObject
{
public int id { get; set; }
public bool is_default { get; set; }
public string name { get; set; }
public int quantity { get; set; }
public string stock { get; set; }
public string unit_cost { get; set; }
}

Here is my JSON result

[{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]

Here is my code to read the result

     public static RootObject GetItems(string user, string key, Int32 tid, Int32 pid)
    {
        // Customize URL according to geo location parameters
        var url = string.Format(uniqueItemUrl, user, key, tid, pid);

        // Syncronious Consumption
        var syncClient = new WebClient();

        var content = syncClient.DownloadString(url);

        return JsonConvert.DeserializeObject<RootObject>(content);

    }

But I am having a problem with this error :

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'avaris_cash_salepoint.BL.UniqueItemDataRootObject' 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.

at this line: return JsonConvert.DeserializeObject(content);

Any help to fix this error ?

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

The answer is


I think the problem you're having is that your JSON is a list of objects when it comes in and it doesnt directly relate to your root class.

var content would look something like this (i assume):

[
  {
    "id": 3636,
    "is_default": true,
    "name": "Unit",
    "quantity": 1,
    "stock": "100000.00",
    "unit_cost": "0"
  },
  {
    "id": 4592,
    "is_default": false,
    "name": "Bundle",
    "quantity": 5,
    "stock": "100000.00",
    "unit_cost": "0"
  }
]

Note: make use of http://jsonviewer.stack.hu/ to format your JSON.

So if you try the following it should work:

  public static List<RootObject> GetItems(string user, string key, Int32 tid, Int32 pid)
    {
        // Customize URL according to geo location parameters
        var url = string.Format(uniqueItemUrl, user, key, tid, pid);

        // Syncronious Consumption
        var syncClient = new WebClient();

        var content = syncClient.DownloadString(url);

        return JsonConvert.DeserializeObject<List<RootObject>>(content);

    }

You will need to then iterate if you don't wish to return a list of RootObject.


I went ahead and tested this in a Console app, worked fine.

enter image description here


You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

This could be You

Before trying to consume your json object with another object just check that the api is returning raw json via the browser api/rootobject, for my case i found out that the underlying data provider mssqlserver was not running and throw an unhanded exception !

as simple as that :)



To read more than one json tip (array, attribute) I did the following.


var jVariable = JsonConvert.DeserializeObject<YourCommentaryClass>(jsonVariableContent);

change to

var jVariable = JsonConvert.DeserializeObject <List<YourCommentaryClass>>(jsonVariableContent);

Because you cannot see all the bits in the method used in the foreach loop. Example foreach loop

foreach (jsonDonanimSimple Variable in jVariable)
                {    
                    debugOutput(jVariable.Id.ToString());
                    debugOutput(jVariable.Header.ToString());
                    debugOutput(jVariable.Content.ToString());
                }

I also received an error in this loop and changed it as follows.

foreach (jsonDonanimSimple Variable in jVariable)
                    {    
                        debugOutput(Variable.Id.ToString());
                        debugOutput(Variable.Header.ToString());
                        debugOutput(Variable.Content.ToString());
                    }

That's because the json you're getting is an array of your RootObject class, rather than a single instance, change your DeserialiseObject<RootObject> to be something like DeserialiseObject<RootObject[]> (un-tested).

You'll then have to either change your method to return a collection of RootObject or do some further processing on the deserialised object to return a single instance.

If you look at a formatted version of the response you provided:

[
   {
      "id":3636,
      "is_default":true,
      "name":"Unit",
      "quantity":1,
      "stock":"100000.00",
      "unit_cost":"0"
   },
   {
      "id":4592,
      "is_default":false,
      "name":"Bundle",
      "quantity":5,
      "stock":"100000.00",
      "unit_cost":"0"
   }
]

You can see two instances in there.


You have an array, convert it to an object, something like:

data: [{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]


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