Parse a json generated by jstree in C#

Viewed 62

I'm currently receiving the following string of an array that was generated from JsTree:

"[
   {
      "id":"j1_1",
      "text":"Root node 1",
      "icon":true,
      "li_attr":{
         "id":"j1_1"
      },
      "a_attr":{
         "href":"#",
         "id":"j1_1_anchor"
      },
      "data":{
         
      },
      "children":[
         {
            "id":"j1_2",
            "text":"Child 1",
            "icon":true,
            "li_attr":{
               "id":"j1_2"
            },
            "a_attr":{
               "href":"#",
               "id":"j1_2_anchor"
            },
            "data":{
               
            },
            "children":[
               
            ]
         }
      ]
   }
]"

I'm trying to deserialize the following item by using

JsTreeModel aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<JsTreeModel>(json);

With JsTreeModel being this class:

    public class JsTreeModel
    {
        [JsonProperty("id")]
        public string id { get; set; }

        [JsonProperty("text")]
        public string text { get; set; }

        [JsonProperty("icon")]
        public string icon { get; set; }

        [JsonProperty("li_attr")]
        public string li_attr { get; set; }

        [JsonProperty("a_attr")]
        public string a_attr { get; set; }

        [JsonProperty("data")]
        public string data { get; set; }
    }

But I'm getting the error`:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AccesosWeb.Entidad.JsTree.JsTreeModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

I think the issue is with how the class is structured, but I don't know how to build it.

1 Answers

This is the model you need in consideration of the json you paste:

You can use the main object:

JsTreeModel myDeserializedClass = JsonConvert.DeserializeObject<JsTreeModel>(json);

and the object is:

public class JsTreeModel 
{
    public List<MyArray> MyArray { get; set; }
}

public class LiAttr
{
    public string id { get; set; }
}

public class AAttr
{
    public string href { get; set; }
    public string id { get; set; }
}

public class Data
{
}

public class Child
{
    public string id { get; set; }
    public string text { get; set; }
    public bool icon { get; set; }
    public LiAttr li_attr { get; set; }
    public AAttr a_attr { get; set; }
    public Data data { get; set; }
    public List<object> children { get; set; }
}

public class MyArray
{
    public string id { get; set; }
    public string text { get; set; }
    public bool icon { get; set; }
    public LiAttr li_attr { get; set; }
    public AAttr a_attr { get; set; }
    public Data data { get; set; }
    public List<Child> children { get; set; }
}
Related