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

118,683

Solution 1

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];

Solution 2

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

Share:
118,683
sakir
Author by

sakir

trying to learn everything.

Updated on July 09, 2022

Comments

  • sakir
    sakir almost 2 years

    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?

  • infl3x
    infl3x about 7 years
    This doesn't really add any value to the question or the other answers.
  • khaled  Dehia
    khaled Dehia almost 7 years
    this will apply only if you have HttpClient Call I marked as the answer is useful Cause the last line has the answer which is Deserialize it as a list of the class JsonConvert.DeserializeObject<List<CategoryModel>>(jsonStrin‌​g);
  • jasie
    jasie about 3 years
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.
  • Marçal Torroella
    Marçal Torroella about 2 years
    Thank you so much for the example, you saved my day... I was missing the point of using a List Of.
  • MD. RAKIB HASAN
    MD. RAKIB HASAN about 2 years
    This approach is really perfect....Thanks!!