How can I deserialize JSON to a simple Dictionary in ASP.NET?

前端 未结 21 2753
粉色の甜心
粉色の甜心 2020-11-21 06:33

I have a simple key/value list in JSON being sent back to ASP.NET via POST. Example:

{ \"key1\": \"value1\", \"key2\": \"value2\"}

21条回答
  •  感情败类
    2020-11-21 07:10

    Annoyingly enough, if you want to use the default model binders, it looks like you will have to use numerical index values like a form POST.

    See the following excerpt from this article http://msdn.microsoft.com/en-us/magazine/hh781022.aspx:

    Though it’s somewhat counterintuitive, JSON requests have the same requirements—they, too, must adhere to the form post naming syntax. Take, for example, the JSON payload for the previous UnitPrice collection. The pure JSON array syntax for this data would be represented as:

    [ 
      { "Code": "USD", "Amount": 100.00 },
      { "Code": "EUR", "Amount": 73.64 }
    ]
    

    However, the default value providers and model binders require the data to be represented as a JSON form post:

    {
      "UnitPrice[0].Code": "USD",
      "UnitPrice[0].Amount": 100.00,
    
      "UnitPrice[1].Code": "EUR",
      "UnitPrice[1].Amount": 73.64
    }
    

    The complex object collection scenario is perhaps one of the most widely problematic scenarios that developers run into because the syntax isn’t necessarily evident to all developers. However, once you learn the relatively simple syntax for posting complex collections, these scenarios become much easier to deal with.

提交回复
热议问题