Tom Beech
Tom Beech

Reputation: 2389

Create javascript object which will convert to JSON then to Dictionary<string, bool>

I have a C# class which contains a property of Dictionary

I have a web-page which contains a list of items i need to cast into this dictionary.

My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.

JsonConvert.Deserialise is expecting JSON in the following format:

  "MyVariableName":{
      "Item 1":true,
      "Item 2":true
   }

I need to know how i can construct this object in JavaScript.

So far, i have tried this without luck:

    var items = [];

    var v = $('#Items :input');
    $.each(v, function(key, val) {

        items.push({
            key: val.value,
            value: val.checked
        });
    });

    JSON.stringify(v, null, 2);

But this returns a json converted value of:

"MyVariableName": [
    {
      "key": "Item 1",
      "value": true
    },
    {
      "key": "Item 2",
      "value": true
    }]

Which in turn does not de-serialize to my dictionary.

Thanks

Upvotes: 1

Views: 2145

Answers (2)

VJ.
VJ.

Reputation: 31

You have to use javascript serialization

One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.

And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.

 var jSerializer = new JavaScriptSerializer();
 var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);

Upvotes: 0

Dan
Dan

Reputation: 9837

Don't make an array; make an object:

var items = {};
$('#Items :input').each(function(i, val) {
    items[val.value] = val.checked;
});

Upvotes: 1

Related Questions