Deserialize JSON with a dot in the property name

I am trying to deserialize JSON with dots in property names in key value format. I use the built-in binding of the ASP.NET MVC model. It seems to interpret the points as object notation, not just an object with a key. Is there a way to make it deserialize correctly as a key value, ignoring the dots? This is important because the data will need to be displayed 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"
    }
}
+4
source share
2 answers

, POST , . , , Id ProgressVM.

, . - JsonValueProviderFactory, Dictionary<string, string> ProgressVM. , ModelBinder , DictionaryValueProvider, Data. , , , JsonValueProviderFactory? , .

JSON , ? :

JavaScript-, jQuery AJAX

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

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

?

+4

json , MVC, .

JSON

{
   "Property.Something": "The value"
}

, [JsonProperty] :

public class JsonModel
{
   [JsonProperty(PropertyName = "Property.Something")]
   public string PropertySomething {get; set;}
}
0

Source: https://habr.com/ru/post/1649727/


All Articles