Java 如何将json字段映射为对象类型和数组类型?
以下是一个Json响应:Java 如何将json字段映射为对象类型和数组类型?,java,Java,以下是一个Json响应: { "info" : { "risk" : <object>, "operations" : <array>, "status" : <string> } } 尝试使用以下方法使用jackson数据绑定: public static Object convertJsonStringToObject(Strin
{
"info" : {
"risk" : <object>,
"operations" : <array>,
"status" : <string>
}
}
尝试使用以下方法使用jackson数据绑定:
public static Object convertJsonStringToObject(String jsonString, Class classToConvert) {
try {
return new ObjectMapper().readValue(jsonString, classToConvert);
} catch (JsonProcessingException e) {
LOG.error("Error when convert object from json.", e.getMessage(), e.getCause());
throw new RuntimeException(e);
}
}
尝试使用以下方法使用jackson数据绑定:
public static Object convertJsonStringToObject(String jsonString, Class classToConvert) {
try {
return new ObjectMapper().readValue(jsonString, classToConvert);
} catch (JsonProcessingException e) {
LOG.error("Error when convert object from json.", e.getMessage(), e.getCause());
throw new RuntimeException(e);
}
}
您的类定义应如下所示:
public class A {
private Info info;
}
public class Info {
private YourClass risk;
private List<YourAnotherClass> operations;
private String status;
}
您的类定义应如下所示:
public class A {
private Info info;
}
public class Info {
private YourClass risk;
private List<YourAnotherClass> operations;
private String status;
}
那么,您是如何执行映射的呢?我只看到一个包含属性的Java类,没有足够的信息。如何反序列化JSON?您是否使用Jackson库?@MaksymRudenko ObjectMapper您只有顶级字段和子项。数组中有哪些类型的项?风险对象有哪些字段?@xdhmoore它未知,它只是声明它是一个对象,另一个是arraySo,您是如何执行映射的?我只看到一个包含属性的Java类,没有足够的信息。如何反序列化JSON?您是否使用Jackson库?@MaksymRudenko ObjectMapper您只有顶级字段和子项。数组中有哪些类型的项?风险对象有哪些字段?@xdhmoore未知,它只是声明它是一个对象,另一个是数组,但我不知道风险中有什么。但我不知道风险是什么。及运作
public static void iterate(JsonNode node) {
if (node.isValueNode()) {
System.out.println(node.toString());
return;
}
if (node.isObject()) {
Iterator<Entry<String, JsonNode>> it = node.fields();
while (it.hasNext()) {
Entry<String, JsonNode> entry = it.next();
iterate(entry.getValue());
}
}
if (node.isArray()) {
Iterator<JsonNode> it = node.iterator();
while (it.hasNext()) {
iterate(it.next());
}
}
}
public static void main(String[] args) {
try {
String jsonStr = ""; // your input string
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node = objectMapper.readTree(jsonStr);
iterate(node);
} catch (Exception e) {
e.printStackTrace();
}
}