2

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 ?

2
  • 1
    Clue. Are the keys of SaleParameters unique? Commented Oct 4, 2018 at 4:23
  • Pardon me, but I didn't get it. If it's working in that editor, why is it not working with the above format ? Commented Oct 4, 2018 at 4:26

1 Answer 1

3

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().

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, since the outer JSON container is an array, it needs to be public IEnumerable<Dictionary<string,string>> SaleParameters { get; set; }. Then you can do SaleParameters.SelectMany(d => d).ToList(); to get a flat list.
@dbc Oops. Yup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.