Johan Johan - 3 months ago 25
JSON Question

Deserialize JSON to anonymous object using JSON.NET

Im using JSON.NET do deserlaize an object, but i cant get it to work with the current structure of the object that im using.

http://dorobantu.me/post/2010/08/22/Deserializing-JSON-to-anonymous-types-in-C.aspx

My object currently looks liks this (i want to pass a list of objects)

[
{
"ID": "Concurrent User",
"FieldType": 190,
"value": ""
},
{
"ID": "System Type",
"FieldType": 191,
"value": null
}
]


Im getting the error:

Cannot deserialize JSON array into type '<>f__AnonymousType1`3[System.String,System.String,System.String]'.


What i need is something similar to example #2, a container object containing a list. Any help is appreciated. Thanks

c# code:

public void GetPoints()
{
string inputFields = HttpContext.Current.Request["inputFields"];

// var test = new { ID = string.Empty, FieldType = string.Empty, Description = string.Empty };

var example = new { containerArray = new { ID = string.Empty, FieldType = string.Empty, Description = string.Empty } };

var fields = JsonConvert.DeserializeAnonymousType(inputFields, example);
}


javascript:

$('.quoteonly :input').live('change keyup', function () {

var $container = $('#quoteonly-container');
var containerObject = {};

var containerArray = [];

$container.find('.quoteonly :input').each(function () {

var fieldType = $(this).data('fieldtype');
var id = $(this).data('id');

var currentObject = { 'ID': id, 'FieldType': fieldType };

switch (fieldType) {

case 190: //textbox
currentObject.value = $(this).val();
break;
case 191: //select
currentObject.value = $(this).val();
break;
case 192: //radio
currentObject.value = $(this).prop('checked') == true ? 1 : 0;
break;
case 193: //checkbox
currentObject.value = $(this).prop('checked') == true ? 1 : 0;
break;
}

containerArray.push(currentObject);
containerObject.containerArray = containerArray;
});

$.ajax({
url: '../SentinelOperationsUI/GenericHandler.ashx',
data: { 'FunctionName': 'GetPoints', 'inputFields': JSON.stringify(containerObject) },
success: function (data) {

}
});

});

Answer
  • 1.

var DTO = { 'items': JSON.stringify(containerObject) };

$.ajax({
            url: '../SentinelOperationsUI/GenericHandler.ashx',
            data: JSON.stringify(DTO),
            success: function (data) {

            }
        });

skip this step if in your code, you get the inputFields string like {items: [{..}]} and not like [{..}, {..}] I just added it for mu testing purpose. The important thing is to get a string inputFields in this format [{..}, {..}]

  • 2.

.

 public void GetPoints()
        {
            string inputFields = HttpContext.Current.Request["items"];
            var test = new[] { new { ID = 0, FieldType = string.Empty, Description = string.Empty } };
            var fields = JsonConvert.DeserializeAnonymousType(inputFields, test);
        }
Comments