Serializing JPA entities to JSON using Jackson

前端 未结 2 456
小蘑菇
小蘑菇 2020-12-29 16:10

Question regarding combination of Jackson/JPA

  1. If there are about 20 entities in current application and I have add Jackson dependency in POM, does it mean a

相关标签:
2条回答
  • 2020-12-29 16:32

    No, you don't need to add @JsonIgnore on every class and if you had tried you would have gotten a compile error, since you can't put it there. Jackson will only work on objects you give to it, it's no magic.

    The Jackson documentation is easily found online, such at its project page on github or on the codehaus website.

    0 讨论(0)
  • 2020-12-29 16:52

    Jackson and JPA don't have anything to do with each other. Jackson is a JSON parsing library and JPA is a persistence framework. Jackson can serialize almost any object - the only requirement being that the object have some kind of recognizable properties (Javabean type properties, or bare fields annotated with @JsonProperty. There is an additional requirement for deserialization, that the target type have a default (no-arg) constructor. So, for example, this is an object that Jackson can serialize:

    // Class with a single Javabean property, "name"
    class Person {
        private String name;
    
        public String getName() { return name ; }
        public String setName(String name) { this.name = name ; }
    }
    

    And here is another:

    // Class with a single field annotated with @JsonProperty
    class Account {
        @JsonProperty("accountNumber")
        private String accountNumber;
    }
    

    And here is yet another:

    @Entity
    public class User {
        @Id
        private Long id;
    
        @Basic
        private String userName;
    
        @Basic
        @JsonIgnore
        private String password;
    
        @Basic
        @JsonIgnore
        private Address address;
    
        // Constructors, getters, setters
    }
    

    The last example shows a JPA entity class - as far as Jackson is concerned it can be serialized just like any other type. But, take note of its fields: when this object is serialized into JSON two of the fields will not be included - 'password' and 'address'. This is because they have been annotated with @JsonIgnore. The @JsonIgnore annotation allows a developer to say 'Hey, its ok to serialize this object, but when you do so don't include these fields in the output'. This exclusion only occurs for the fields of this object, so for example, if you included an Address field in another class, but did not mark the field as ignorable, it would be serialized.

    To prevent serialization of a type in all cases, regardless of context, use the @JsonIgnoreType annotation. When used on a type it basically means 'I dont care where this type is used, never serialize it'.

    0 讨论(0)
提交回复
热议问题