我有一个像这样的 json 数组:
数据:
[
{
image_url:"www",
testimonial_text: "The standard chunk of Lorem Ipsum used since the,
name: "Rohith",
designation: "Architect"
}
]
但是我需要像这样使用java来转换它:
数据:
[
{
image_url:"www",
testimonial_text: "The standard chunk of Lorem Ipsum used since the,
name: "Rohith",
data2:[{ designation: "Architect"}]
}
]
使用 Jackson JSON API 解析器,https://github.com/FasterXML/jackson
String json = " [{ image_url:\"www\", testimonial_text: \"The standard chunk of Lorem Ipsum used since the\", name: \"Rohith\", designation: \"Architect\" }, "
+ "{ image_url:\"www\", testimonial_text: \"The standard chunk of Lorem Ipsum used since\", name: \"Rohith\", designation: \"Architect\" }]";
byte[] jsonData = json.getBytes();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// create JsonNode
JsonNode rootNode = objectMapper.readTree(jsonData);
ObjectNode createDesignationNode = objectMapper.createObjectNode();
Iterator<JsonNode> iterator = rootNode.iterator();
while (iterator.hasNext()) {
JsonNode jsonNode = (JsonNode) iterator.next();
createDesignationNode.put("designation", jsonNode.get("designation"));
ArrayNode createData2Array = objectMapper.createArrayNode();
createData2Array.add(createDesignationNode);
((ObjectNode) jsonNode).remove("designation");
((ObjectNode) jsonNode).put("data2", createData2Array);
}
PrintStream out = System.out;
objectMapper.writeValue(out, rootNode);
结果[{"image_url":"www","testimonial_text":"Lorem Ipsum 的标准块","name":"Rohith","data2":[{"designation":"Architect"}] },{"image_url":"www","testimonial_text":"Lorem Ipsum 使用的标准块","name":"Rohith","data2":[{"designation":"Architect"}]} ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句