且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于对象类型反序列化JSON

更新时间:2022-02-12 08:35:49

如果您使用 Jackson 将JSON输入解析为Map,您可以快速访问类型信息。然后,您可以将对象创建为必需的类,并使用 ObjectMapper.convert 从您从Jackson获得的地图配置对象。

If you use Jackson to parse the JSON input into a Map, you can quickly access the type information. You can then create the object as the required class and use ObjectMapper.convert to configure the object from the Map you got from Jackson.

以下是一个示例:

public class Test1 {
private String f;
private String b;

public void setFoo(String v) { f = v; }

public void setBim(String v) { b = v; }

public String toString() { return "f=" + f + ", b=" + b; }


public static void main(String[] args) throws Exception {
    String test = "{ \"foo\":\"bar\", \"bim\":\"baz\" }";
    ObjectMapper mapper = new ObjectMapper();
    HashMap map = mapper.readValue(new StringReader(test), HashMap.class);
    System.out.println(map);
    Test1 test1 = mapper.convertValue(map, Test1.class);
    System.out.println(test1);
}
}