2015-04-22 55 views
0

我有一個JSON字符串是這樣的:如何通過從原始字符串中提取幾個字段來創建新的JSON字符串?

{"customerid":null,"clientid":"123456","test_id":"98765","pet_id":0,"qwer_id":0,"timestamp":1411811583000} 

我需要另一個JSON字符串是這樣的:

{"customerid":"System.nanoTime()","test_id":"98765","timestamp":1411811583000} 

所以基本上定了原始JSON字符串,我需要提取「客戶ID」, 「test_id」和「timestamp」,然後創建一個新的JSON字符串。此外,新JSON中的「customerid」的值將爲System.nanoTime()

下面是我的代碼:

JsonObject originalJSONString = new JsonObject(); 

// some code here 

Gson gson = new GsonBuilder().serializeNulls().create(); 
System.out.println(gson.toJson(originalJSONString)); 

// make a new JSON String now 

我在我的例子使用GSON。我很困惑如何從原始的json中提取我感興趣的相關字段,然後從中創建一個新的json?

回答

1

假設originalJSONString代表

{"customerid":null,"clientid":"123456","test_id":"98765","pet_id":0,"qwer_id":0,"timestamp":1411811583000} 

你可以用一些嘗試像

JsonObject newJsonObject = new JsonObject(); 

newJsonObject.addProperty("customerid", "System.nanoTime()");//new property 
newJsonObject.add("test_id", originalJSONString.get("test_id"));//copy property 
newJsonObject.add("timestamp", originalJSONString.get("timestamp"));//copy property 

System.out.println(gson.toJson(newJsonObject)); 

輸出:{"customerid":"System.nanoTime()","test_id":"98765","timestamp":1411811583000}

0

您可以將JSON字符串轉換成地圖,然後只得到關鍵/你需要的值。

類似:

import org.codehaus.jackson.map.ObjectMapper; 
import org.codehaus.jackson.type.TypeReference; 

.... 

//convert JSON string to Map  
map = mapper.readValue(jsonString, new TypeReference<HashMap<String,String>>(){}); 

... 

//add key and values in a new one  
JsonObject newJsonObject = new JsonObject(); 
相關問題