Home > OS >  not able to convert json string into c# object , getting error- because the type requires a JSON arr
not able to convert json string into c# object , getting error- because the type requires a JSON arr

Time:06-22

i want to convert json data into c#, im getting error in converting json string into C# object.

Code

   List<Root> list = new List<Root>();
        list = JsonConvert.DeserializeObject<List<Root>>(jsonString);

json data

    {
        "Set1": [
            {
                "TotalColumns": "5",
            "Header": "Date",
            "DataType": "DateTime",
            "MaxLength": "8"
        },
        {
            "TotalColumns": "5",
            "Header": "Code",
            "DataType": "Int",
            "MaxLength": "6"
        },
        {
            "TotalColumns": "5",
            "Header": "Description",
            "DataType": "String",
            "MaxLength": "500"
        },
        {
            "TotalColumns": "5",
            "Header": "Qty",
            "DataType": "Int",
            "MaxLength": "6"
        },
        {
            "TotalColumns": "5",
            "Header": "Amount",
            "DataType": "Double",
            "MaxLength": "100"
        }
    ]
}

C# Class

public class Set1
    {
        public string TotalColumns { get; set; }
        public string Header { get; set; }
        public string DataType { get; set; }
        public string MaxLength { get; set; }
    }

public class Root
{
    public List<Set1> Set1 { get; set; }
}

error

deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[....Root]' because the type requires a JSON array

CodePudding user response:

You're actually trying to cast the JSON as a List<Root>, but the JSON doesn't contain an array of the Root class.

What you could do is to deserialize your JSON as a Root instance instead of a List<Root>, but if you absolutely want to deserialize it into a List<Root>, your problem is in the code that generated the JSON, it doesn't serialized a List but a single instance of Root.

CodePudding user response:

you have 2 variants

  1. Get a root object
Root root = JsonConvert.DeserializeObject<Root>(jsonString);
  1. Get a list
 List<Set1> Set1 = JObject.Parse(jsonString)["Set1"].ToObject<List<Set1>>();
  • Related