0

I have a class that looks similar to this

public class Demo
{
    [JsonProperty("variables")]
    [JsonExtensionData]
    IDictionary<string, object> Variables { get; set; } = new Dictionary<string, object>();
}

My sample json looks like this

{
    "variables" : [
        {
            "a" : "1"
        }
    ]
}

When I post my data, Demo.Variables looks like this

{[variables, [
  {
    "a": "1"
  }
]]}

What I want is:

[{
  "a": "1"
}]
stuartd
  • 70,509
  • 14
  • 132
  • 163
CBC_NS
  • 1,961
  • 4
  • 27
  • 47
  • 1
    Does "[How can I deserialize JSON to a simple Dictionary in ASP.NET?](https://stackoverflow.com/q/1207731/1364007)" help? – Wai Ha Lee Jan 15 '19 at 16:22
  • @WaiHaLee No. I want to be able to post my form data, and have the json property deserialize properly. In the above question you mentioned, they are taking a json string and deserializing. When I observe Demo.Variables I see [0] : {[variables, [ { "a": "1" } ]]} Rather than [0] "key" : "x", "value" : "1" – CBC_NS Jan 15 '19 at 16:26

1 Answers1

1

You may need to look at your data a little different.

This JSON:

{
    "variables" : [
        {
            "a" : "1"
        }
    ]
}

Can be viewed as a collection of dictionaries like this:

public class Demo
{        
    public IEnumerable<Dictionary<string, string>> Variables { get; set; }
}

Then to get the output you requested:

[{
  "a": "1"
}]

Just serialize/deserialize like so:

public void Serialization()
{
    var dto = JsonConvert.DeserializeObject<Demo>(json);                       
    var postData = JsonConvert.SerializeObject(dto.Variables);
}

postData will then deserialize back to IEnumerable<Dictionary<string, string>> just as indicated by the JSON [{"a":"1"}]

JSteward
  • 6,833
  • 2
  • 21
  • 30