如何通过从原始字符串中提取几个字段来创建新的JSON字符串?
问题描述:
我有一个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?
答
假设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}
答
您可以将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();