繁体   English   中英

如何使用对象类型和数组类型映射 json 字段?

[英]How can I map json fields with object type and array type?

这是 Json 中的响应:

{

  "info" : {
      "risk" : <object>,
      "operations" : <array>,
      "status" : <string>
  }
}

我如何在课堂上映射它? 这是我尝试过的类映射:

public class Info {
 
    private Object risk;
    private Array operations;
    private String status;

}

尝试通过以下方法使用 jackson databind https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

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);
        }
    }
Info info = (Info) JsonConverter.convertJsonStringToObject(stringJson, Info.class);    

您的类定义应如下所示:

public class A {
    private Info info;
}
    
public class Info {
    private YourClass risk;
    private List<YourAnotherClass> operations;
    private String status;
}

您可以使用 Jackson 反序列化 json 字符串。 注意你的目标类类型应该是A.class

如果不知道json字符串的内容,可以使用JsonNode进行迭代。 例如:

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM