2014-03-12 73 views
0

您好我想從JSON爲另一種格式像below.My JSON格式轉換爲類似下面 我嘗試使用Json.Net plugin.but找不到解決如何JSON格式轉換爲另一種格式

[ 
{ 

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

}, 
{ 

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

}] 

想在下面的格式轉換

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

我嘗試使用下面的鏈接

JSON Serialize List<KeyValuePair<string, object>>

+1

的輸入是無效的JSON。有尾隨逗號。 – 2014-03-12 13:37:05

回答

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); 
} 
+0

這是.NET還是Java? – 2014-03-12 13:37:31

+0

java哦抱歉,我沒有注意到它,但你可以轉換它我猜.. –

3

這裏是你可以用Json.Net您的JSON從一種格式轉換爲另一種快捷方式(假定輸入是有效的JSON - 因爲你已經張貼,也有bundleValues後多餘的逗號,這是我在下面的代碼已經移除):

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); 

輸出:

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

嗨你爲什麼初始化JSON作爲一個字符串。我得到JSON從通用.so我得到錯誤的行JArray array = JArray.Parse( JSON);作爲參數不能將模型轉換爲字符串 – King

+0

雅其工作good.But我想在asp.net.this這是在控制檯應用程序的工作良好 – King

+0

除了'Console.WriteLine()',以防止它從在ASP.NET中使用。 –

相關問題