简体   繁体   中英

JSON deserialization returns {null,null} for KeyValuePair

I've declared the below key:value pair in JSON:

"saleParameters": [
        {"saleName":"FlashSale2018"},
  ]

I'm mapping the above using the below property in my contract class:

    [JsonProperty("saleParameters")]
    public IEnumerable<KeyValuePair<string,string>> SaleParameters { get; set; }

But for some reason, I always receive null values in SaleParameters after deserialization. I'm using NewtonSoft.JSON for JSON serialize/deserialize, code is running on .net core.

Any idea on why this is happening and how to solve this ?

The problem is that your current code expects JSON like this :

"saleParameters": [
    {"Key": "saleName", "Value": "FlashSale2018"}]
]

You should use a dictionary instead:

public IEnumerable<IDictionary<string,string>> SaleParameters { get; set; }

This will deserialize "saleName" as they key and "FlashSale2018" as the value. And, if you really need IEnumerable<KeyValuePair<string, string>> , you can call SaleParameters.SelectMany(p => p). ToEnumerable() SaleParameters.SelectMany(p => p). ToEnumerable() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM