简体   繁体   中英

How can I deserialize a json string List<Dictionary<string,int>> using JQuery?

Many thanks in advance for your help.

I have the following code in an action which returns a json serialized string of List<Dictionary<string,int>> , but I am struggling to get the data into a usable format in the view, using JQuery. I want to be able to iterate through each dictionary.

I have done this before using a List, which worked, so I could I suppose create a new model but I am sure I should be able to deserialize this.

I would greatly appreciate it if someone could suggest a way to deserialize this data or a better way to send the data in the first place.

MenuController:

public JsonResult Populate(string id) {
    // Get and process data, creating all, a List<Dictionary<string,int>>
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    string json = serializer.Serialize((object)all);
    return Json(json, JsonRequestBehavior.AllowGet);
}

I also tried the following instead of using the JavascriptSerielizer, but it had the same result:

return Json(JsonConvert.SerializeObject(all), JsonRequestBehavior.AllowGet);

cshtml jquery:

<script type="text/javascript">
    $.get('@Url.Action("Populate","Menu")', { id: "MO" }, function (data) {
        console.log(data);
        var obj = jQuery.parseJSON(data);
        console.log('obj: ' + obj);
        for (var o in obj) {
            console.log('o is: ' + o);
        }    
    })
    .done(function (d) {
        console.log('done: ' + d);
    })
    .fail(function (d) {
        console.log('fail: ' + d);
    });
</script>

In the console I get:

data

[{"foo":2,"bar":0,"ray":3,"doh":1},{"mee":1,"so":0,"lah":2,"far":0}]

obj

obj: [object Object],[object Object]

o

o is: 0
o is: 1

done

done: [{"foo":2,"bar":0,"ray":3,"doh":1},{"mee":1,"so":0,"lah":2,"far":0}]

Many thanks for your help.

So lists get translated to arrays and dictionaries to objects, so it seems that everything is working fine. In Javascript, you have been handed an array with two objects in it. You could iterate each object (which is the translated dictionary) as follows:

var data;// your downloaded JSON object
for(var i = 0;i < data.length; ++i) //for enumerating array
{
     var obj = data[i];
     for(var propName in obj) //for enumerating the properties of an object
     {
         var value = obj[propName];
         alert("item : " + i + " : prop : " + propName + " : value : " + value);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM