Deserialize JSON with dot in property name

前端 未结 2 1951
孤街浪徒
孤街浪徒 2021-01-18 10:43

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 do

2条回答
  •  醉梦人生
    2021-01-18 11:47

    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 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(data);
        // Rest of code here
    }
    

    Is this answering your question?

提交回复
热议问题