Deserialize JSON with dot in property name

前端 未结 2 1955
孤街浪徒
孤街浪徒 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:36

    I came here looking for a way to deserialize a json string into a model, and while the question here is solved though the MVC framework, it did not solve my issue.

    Given a json string of

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

    I found that using the [JsonProperty] attribute I could deserialize the string into my model like this:

    public class JsonModel
    {
       [JsonProperty(PropertyName = "Property.Something")]
       public string PropertySomething {get; set;}
    }
    
    0 讨论(0)
  • 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<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?

    0 讨论(0)
提交回复
热议问题