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?
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.
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.
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 .
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];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With