当嵌套 JSON 中出现相同的字段名称时,将 JSON 解析为 java 对象

以下是我的JSON:


{

  "time":{

    "date":{

      "year":2017,

      "month":3,

      "day":12

     },

    "time":{

      "hour":10,

      "minute":42,

      "second":42,

      "nano":810000000

     }

   },

"name":"Jon",

"message":{

"product":"orange"

"price":2000

}

}

“时间”字段有一个嵌套的“时间”字段。我如何使用杰克逊解析它到java对象。任何人都可以告诉我正确的方法吗?


白衣染霜花
浏览 226回答 3
3回答

jeck猫

您可以创建如下类: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 反序列化为对象,例如:JacksonjsonJavaObjectObjectMapper 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);

DIEA

如果你只需要内部对象,你可以用一种快速的方式做到这一点: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 stringString 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 JsonNodePojo pojo = mapper.treeToValue(jsonRoot.at("/time/time"), Pojo.class); //create Pojo instance from inner time objectSystem.out.println(pojo); //see if it worked这打印:10:42:42:810000000

明月笑刀无情

使用杰克逊库ObjectMapper jsonMapper= new ObjectMapper();YourCorrespondingObject object = jsonMapper.readValue("your json as string...", YourCorrespondingObject.class);首先构建对象,填充它并转换为字符串更容易,以确保它等于现有字符串,例如:String jsonInString = mapper.writeValueAsString(object);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java