简体   繁体   中英

Json formatting from dictionary C#

Hello I have a dictionary that I am using.

Dictionary<string, string> myProperties

I am trying to format this into a JSON and am having difficulties. I need it to be like this:

    {
     "properties": [
      {
        "property": "firstname",
        "value": "John"
      },
      {
        "property": "lastname",
        "value": "Doe"
      },
      {
        "property": "country",
        "value": "united states"
      }
    ]
  }

Currently I am using Json.NET to serialize the dictionary but that gives me this:

{
  "country": "united states",
  "firstname": "John",
  "lastname": "Doe"
}

Can anybody help me format this into what I need. Any help would be much appreciated.

You get there by sending the result from .Select() to the json serializer wrapped in a anon class, but I would suggest that you use real classes if you intend to build something larger.

JsonConvert.SerializeObject(
  new {properties = myProperties.Select(kv => new { property = kv.Key, value = kv.Value})}
  ,Formatting.Indented);

This will give you

{
  "properties": [
    {
      "property": "firstname",
      "value": "John"
    },
    {
      "property": "lastname",
      "value": "Doe"
    },
    {
      "property": "country",
      "value": "united states"
    }
  ]
} 

在N0b1ts上构建答案:

JsonConvert.SerializeObject(new { properties = myProperties.Select(kvp => new { property = kvp.Key, value = kvp.Value }).ToList() }, Formatting.Indented);

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