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

时间:2019-03-28 08:49:13

标签: java json parsing jackson gson

下面是我的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对象。谁能告诉我正确的方法吗?

3 个答案:

答案 0 :(得分:2)

您可以创建如下类:

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
}

完成后,您可以使用Jacksonjson字符串反序列化为JavaObject对象,例如:

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

答案 1 :(得分:1)

如果仅需要内部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

答案 2 :(得分:0)

使用Jackson library

ObjectMapper jsonMapper= new ObjectMapper();
YourCorrespondingObject object = jsonMapper.readValue("your json as string...", YourCorrespondingObject.class);

首先,您可以更轻松地构建对象,填充对象并转换为字符串,以确保它等于您现有的字符串,例如:

String jsonInString = mapper.writeValueAsString(object);