0

Hi I want to convert json from one format to another like below.My Json format is like below I tried using Json.Net plugin.but couldn't find solution

[
{

    "bundleKey": "title",
    "bundleValue": "Manage cost code",

},
{

    "bundleKey": "name",
    "bundleValue": "steve",

}]

Want to convert in the following format

[{"title":"Manage cost code"},{"name":"steve"}]

I am tried using following link

JSON Serialize List<KeyValuePair<string, object>>

Community
  • 1
  • 1
King
  • 53
  • 1
  • 9

2 Answers2

3

Here is a quick way you can use Json.Net to convert your JSON from one format to the other (assuming the input is valid JSON--as you've posted it, there are extra commas after the bundleValues, which I have removed in the code below):

string json = @"
[
    {
        ""bundleKey"": ""title"",
        ""bundleValue"": ""Manage cost code""
    },
    {
        ""bundleKey"": ""name"",
        ""bundleValue"": ""steve""
    }
]";

JArray array = JArray.Parse(json);
JArray outputArray = new JArray();
foreach (JObject item in array)
{
    JObject outputItem = new JObject();
    outputItem.Add(item["bundleKey"].ToString(), item["bundleValue"]);
    outputArray.Add(outputItem);
}

string outputJson = outputArray.ToString(Formatting.None);
Console.WriteLine(outputJson);

Output:

[{"title":"Manage cost code"},{"name":"steve"}]
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • hi why you initialize Json as a string .I am getting Json from generic .so am getting error in the line JArray array = JArray.Parse(json); as a argument can not convert model to string – King Mar 13 '14 at 06:18
  • Ya its working good.But i want this in asp.net.this is working good at console application – King Mar 13 '14 at 08:02
  • There's nothing in the above code except for `Console.WriteLine()` that prevents it from being used in ASP.NET. – Brian Rogers Mar 13 '14 at 14:40
1
   private static List convert(List<Map> jsonNode) {
    if(jsonNode == null)
        return null;
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    for (Map json :  jsonNode) {
        Map tmp = new HashMap();
        putVaue(tmp, json);
        result.add(tmp);
    }
    return result;
}

private static void putVaue(Map<String, Object> result,
    Map<String, Object> jsonNode) {
    String key = (String) jsonNode.get("bundleKey");
    Object value = jsonNode.get("bundleValue");
    result.put(key, value);
}
Akash Yadav
  • 861
  • 7
  • 11