我有一个像这样的 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 字符串,我只需要提取“customerid”、“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}
关于java - 如何通过从原始字符串中提取一些字段来生成新的 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809506/