3 回答
TA贡献1909条经验 获得超7个赞
您可以创建如下类:
class JavaObject {
private TimeObject time;
private String name;
//other fields
//getters and setters
}
class TimeObject {
private Date date;
private Time time;
//getters and setters
}
class Date {
private int year;
private int month;
private int day;
//getters and setters
}
class Time {
private int hour;
private int minute;
private int second;
private long nano;
//getters and setters
}
完成后,您可以使用 将 String 反序列化为对象,例如:JacksonjsonJavaObject
ObjectMapper objectMapper = new ObjectMapper();
JavaObject javaObject = objectMapper.readValue("{\n" +
" \"time\":{\n" +
" \"date\":{\n" +
" \"year\":2017,\n" +
" \"month\":3,\n" +
" \"day\":12\n" +
" },\n" +
" \"time\":{\n" +
" \"hour\":10,\n" +
" \"minute\":42,\n" +
" \"second\":42,\n" +
" \"nano\":810000000\n" +
" }\n" +
" },\n" +
"\"name\":\"Jon\"}", JavaObject.class);
System.out.println(javaObject);
TA贡献1820条经验 获得超2个赞
如果你只需要内部对象,你可以用一种快速的方式做到这一点:time
// your POJO class
// (public fields sould be private with getter & setter, of course)
public class Pojo {
public int hour;
public int minute;
public int second;
public long nano;
@Override
public String toString() {
return hour + ":" + minute + ":" + second + ":" + nano;
}
}
然后:
//your json string
String jsonString = "{\"time\":{\"date\":{\"year\":2017,\"month\":3,\"day\":12},"
+ "\"time\":{\"hour\":10,\"minute\":42,\"second\":42,\"nano\":810000000}},"
+ "\"name\":\"Jon\",\"message\":{\"product\":\"orange\",\"price\":2000}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonRoot = mapper.readTree(jsonString); //parse string to JsonNode
Pojo pojo = mapper.treeToValue(jsonRoot.at("/time/time"), Pojo.class); //create Pojo instance from inner time object
System.out.println(pojo); //see if it worked
这打印:
10:42:42:810000000
TA贡献1828条经验 获得超4个赞
使用杰克逊库
ObjectMapper jsonMapper= new ObjectMapper();
YourCorrespondingObject object = jsonMapper.readValue("your json as string...", YourCorrespondingObject.class);
首先构建对象,填充它并转换为字符串更容易,以确保它等于现有字符串,例如:
String jsonInString = mapper.writeValueAsString(object);
添加回答
举报