简体   繁体   中英

Parse complex JSON object with Jackson

I need to parse relatively complex JSON with Jackson library. Could you guys advice what Java class structure should I have and what Jackson approach to use to parse the following JSON object.

It is like this:

{
  "firstField": "Something One",
  "secondField": "Something Two",
  "thirdField": [
    {
      "thirdField_one": "Something Four",
      "thirdField_two": "Something Five"
    },
    {
      "thirdField_one": "Something Six",
      "thirdField_two": "Something Seven"
    }
  ],
  "fifthField": [
    {
      "fifthField_one": "Something… ",
      "fifthField_two": "Something...",
      "fifthField_three": 12345
    },
    {
      "fifthField_one": "Something",
      "fifthField_two": "Something",
      "fifthField_three": 12345
    }
  ]
}

I'm more versed with Gson, but I think this should work.

See StaxMan's note below:

Jackson does not automatically detect private fields (it can be configured to, with @JsonAutoDetect or globally). So fields should either be private, annotated with @JsonProperty, or have matching public getter.

public class MyClass {
    private String firstField, secondField;
    private ThirdField thirdField;
    private FifthField fifthField;

    public static class ThirdField {
        private List<ThirdFieldItem> thirdField;
    }

    public static class ThirdFieldItem {
        private String thirdField_one, thirdField_two;
    }

    public static class FifthField {
        private List<FifthFieldItem> fifthField;
    }

    public static class FifthField {
        private String fifthField_one, fifthField_two;
        private int fifthField_three;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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