Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class like this:

public class MyStok
{
    public int STId { get; set; }
    public int SM { get; set; }
    public string CA { get; set; }
    public string Br { get; set; }
    public string BNo { get; set; }
    public decimal Vat { get; set; }
    public decimal Price { get; set; }
}

I deserialize like this:

string sc = e.ExtraParams["sc"].ToString();
MyStok myobj = JSON.Deserialize<MyStok>(sc);

My output seems to be like this (string sc) on fiddler:

[
    {
        "STId": 2,
        "CA": "hbh",
        "Br": "jhnj",
        "SM": 20,
        "Vat": 10,
        "Price": 566,
        "BNo": "1545545"
    }
]

But I get the error:

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

What is wrong in that code?

like image 987
sakir Avatar asked Jul 20 '13 11:07

sakir


People also ask

Can not deserialize JSON array?

To 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<T>) that can be deserialized from a JSON object.

How do you serialize and deserialize a JSON object in Python?

For serializing and deserializing of JSON objects Python “__dict__” can be used. There is the __dict__ on any Python object, which is a dictionary used to store an object's (writable) attributes. We can use that for working with JSON, and that works well.

What is Jsonconvert DeserializeObject?

DeserializeObject(String, Type,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, Type, JsonSerializerSettings) Deserializes the JSON to the specified .


2 Answers

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];
like image 102
Sergey Kalinichenko Avatar answered Oct 17 '22 14:10

Sergey Kalinichenko


For array type Please try this one.

 List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc, typeof(List<MyStok>));

Please See here for details to deserialise Json

like image 26
Janty Avatar answered Oct 17 '22 13:10

Janty