How can I convert Json key:value into value:value in C#?

Viewed 414

I am reading a resource file in C# and converted it to the JSON string format. Now I want to convert that JSON string's value as keys.

Example,

[
 {
  "key": "CreateAccount",
  "text": "Create Account"
 },
 {
  "key": "EmailAddress",
  "text": "Email Address"
 }
]

So I just want to make the above json string into "Key:text" as like below,

[
 {
  "CreateAccount": "Create Account"
 },
 {
  "EmailAddress": "Email Address"
 }
]

My C#,

var obj = new
 {
   Lang=XElement.Parse(_FileDataAsText)
    .Elements("data")
    .Select(el => new
          {
                    key= el.Attribute("name").Value,
                    text = el.Element("value").Value
          }.ToList()
 };

 string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
1 Answers

Create a class to represent the inner JSON objects:

public class RootObject
{
    public string Key { get; set; }
    public string Text { get; set; }
}

Then deserialize the JSON array to List<RootObject> using Json.NET, project the object key and text to key value pairs inside a Dictionary<string, string> using Enumerable.Select, then serialize the result as List<Dictionary<string, string>>.

using Newtonsoft.Json;

...

var json = @"[{""key"": ""CreateAccount"",""text"": ""Create Account""},{""key"": ""EmailAddress"",""text"": ""Email Address""}]";

 var deserializedJson = JsonConvert
    .DeserializeObject<List<RootObject>>(json);

var result = deserializedJson
    .Select(obj => new Dictionary<string, string> { 
        { obj.Key, obj.Text } 
    })
    .ToList();

var serializedJson = JsonConvert.SerializeObject(result, Formatting.Indented);

Console.WriteLine(serializedJson);

Output:

[
  {
    "CreateAccount": "Create Account"
  },
  {
    "EmailAddress": "Email Address"
  }
]
Related