Jayden Meyer Jayden Meyer - 4 months ago 18
JSON Question

Deserialize JSON with dot in property name

I am trying to deserialize JSON with dots in the property names into a key-value format. I am using the inbuilt ASP.NET MVC model binding. It seems to be interpreting the dots as a object notation instead of just a key-value object. Is there any way to make it deserialize correctly as a key value ignoring the dots? This is important as the data will need to be output again in this format.

Controller Action

[HttpPost]
public ActionResult SaveProgress(int id, ProgressVM data)
{
// ProgressVM Data property has an item with key "prop" and a null value, nothing else
}


View model

public class ProgressVM
{
public int ID { get; set; }
public Dictionary<string, string> Data { get; set; }
}


JSON Example

{
"ID": 123,
"Data": {
"prop.0.name": "value",
"prop.0.id": "value",
"prop.1.name": "value",
"prop.2.name": "value",
"prop.3.name": "value"
}
}

Answer

First of all, when passing parameters in a POST action, you pass only one parameter and not multiple. So, try to create a model where the Id and the ProgressVM model will be included.

Now, for the issue with the deserialization. Something seems wrong with the JsonValueProviderFactory class, as it does not bind the nested Dictionary<string, string> from ProgressVM model. I know, because I tried to create a ModelBinder for this model, but it fails on the DictionaryValueProvider, not binding the Data property. Unfortunately, I haven't searched why this is happening, is it a bug on JsonValueProviderFactory? I do not know, so I moved quickly to another workaround.

Why don't you try to give the JSON string to the controller instead of the model, and then in the body of the controller deserialize the input? Look at the example below:

JavaScript code, using jQuery AJAX to post data

var data = {
    "ID": 123,
    "Data": {
        "prop.0.name": "value",
        "prop.0.id": "value",
        "prop.1.name": "value",
        "prop.2.name": "value",
        "prop.3.name": "value"
    }
}; 

$.ajax({
    url: '@Url.Action("SaveProgress", "Home")',
    data: { "data": JSON.stringify(data) },
    method: "POST"
});

ASP.NET MVC Controller action

[HttpPost]
public ActionResult SaveProgress(string data)
{
    var json = JsonConvert.DeserializeObject<ProgressVM>(data);
    // Rest of code here
}

Is this answering your question?

Comments