简体   繁体   English

用Jackson解析复杂的JSON对象

[英]Parse complex JSON object with Jackson

I need to parse relatively complex JSON with Jackson library. 我需要用Jackson库解析相对复杂的JSON。 Could you guys advice what Java class structure should I have and what Jackson approach to use to parse the following JSON object. 你们能否建议我应该具有什么样的Java类结构以及用于解析以下JSON对象的Jackson方法。

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. 我更精通Gson,但我认为这应该可行。

See StaxMan's note below: 请参阅下面的StaxMan注意:

Jackson does not automatically detect private fields (it can be configured to, with @JsonAutoDetect or globally). Jackson不会自动检测私有字段(可以使用@JsonAutoDetect或全局将其配置为私有字段)。 So fields should either be private, annotated with @JsonProperty, or have matching public getter. 因此,字段应该是私有的,并用@JsonProperty注释,或具有匹配的公共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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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