Skip to main content

Jackson



<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.6</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.6</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.6</version>
</dependency>

CBOR encoded data with Jackson

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-cbor</artifactId>
    <version>2.9.6</version>
</dependency>    


In order to read and write MessagePack encoded data

<dependency>
    <groupId>org.msgpack</groupId>
    <artifactId>jackson-dataformat-msgpack</artifactId>
    <version>0.8.16</version>
</dependency>

com.fasterxml.jackson.databind.ObjectMapper [databind has objectMapper]

ObjectMapper is because it maps JSON into Java Objects (deserialization), or Java Objects into JSON (serialization).


Add caption

Custom Deserializer 

 1. Create SimpleModule
 2.   Register   objectmapper.registerModule(module);

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public Car deserialize(JsonParser parser, DeserializationContext deserializer) 
throws IOException {


Custom Serializer

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

  public void serialize(Car car, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)

JsonNode

com.fasterxml.jackson.databind.JsonNode is Jackson's tree model

ObjectMapper objectMapper = new ObjectMapper();

JsonNode jsonNode = objectMapper.readTree(json)
ObjectMapper objectMapper = new ObjectMapper();

JsonNode jsonNode = readJsonIntoJsonNode();

String json = objectMapper.writeValueAsString(jsonNode);
  • Read + Write Annotations
  •  is used to tell Jackson to ignore a certain property (field) of a Java object.
  •  @JsonIgnore
        public long    personId = 0;
  • @JsonIgnoreProperties({"firstName", "lastName"})
    public class PersonIgnoreProperties {
    
     @JsonIgnoreType
        public static class Address {
            public String streetName  = null;
            public String houseNumber = null;
            public String zipCode     = null;
            public String city        = null;
            public String country     = null;
        }

    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY ) public class PersonAutoDetect { private long personId = 123; public String name = null;  
    • @JsonSetter  use it when property name is not same as field name in class
  •    public long getPersonId() { return this.personId; }
        @JsonSetter("id")
        public void setPersonId(long personId) { this.personId = personId; }
  • is used for calling unrecognized properties
    we must add the @JsonCreator annotation to the constructor. But that alone is not enough. We must also annotate the parameters of the constructor to tell Jackson which fields from the JSON object to pass to which constructor parameters.
    @JsonCreator
        public PersonImmutable(
                @JsonProperty("id")  long id,
                @JsonProperty("name") String name  ) {
    
            this.id = id;
            this.name = name;
        }

    The Jackson annotation @JacksonInject is used to inject values into the parsed objects, instead of reading those values from the JSON
    The Jackson annotation @JsonDeserialize is used to specify a custom de-serializer class for a given field in a Java object.

  • Write Annotations
    1. @JsonInclude
  • The Jackson annotation @JsonInclude tells Jackson only to include properties under certain circumstances. For instance, that properties should only be included if they are non-null, non-empty, or have non-default values. 

  • @JsonInclude(JsonInclude.Include.NON_EMPTY)
    public class PersonInclude {
    
        public long  personId = 0;
        public String name     = null;
    
    }
  • same as setter except its getter

public class PersonSerializer {

    public long   personId = 0;
    public String name     = "John";

    @JsonSerialize(using = OptimizedBooleanSerializer.class)
    public boolean enabled = false;
}













Jackson Annotations

@JsonIdentityInfo allows to serialize a POJO by id but only when it is encountered second time during serialization.
 @JsonIdentityReference serialize the POJO by id the first time it is encountered.


package example;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
                  property = "id")
@JsonIdentityReference(alwaysAsId = true)
public class Student {}
}

https://www.logicbig.com/tutorials/misc/jackson/json-identity-reference.html
____________________________________________________________________________

@JsonIgnore instead is a member-level or method-level annotation, which expects that the properties to be excluded are marked one by one.

@JsonIgnore@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "reroute")
public Set getEmployee() {
   return this.employee;
}

@JsonIgnoreProperties is an annotation at the class level and it expects that the properties to be excluded would be explicitly indicated in the form of a list of strings.
@JsonPropertyOrder : Defines ordering to use while serializing

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({ "id", "doj", "employee"})
public class EmploymentDetails {

@JsonIgnoreProperties(value = {"employee"}, ignoreUnknown = true)
      @JsonPropertyOrder({ "id", "doj", "employee"})
public class EmploymentDetails {
______________________________________________________________________________
https://www.logicbig.com/tutorials/misc/jackson.html


@JsonIgnoreType can be used to ignore the whole class,
https://www.logicbig.com/tutorials/misc/jackson/json-ignore-type.html



@JacksonInject annotation is used to indicate that value of annotated property will be injected during deserialization.
This is useful if we want to add additional information which is not included in 

https://www.logicbig.com/tutorials/misc/jackson/jackson-inject.html

the source JSON.

@JsonAlias({"department", "employeeDept" })
private String dept;
_______________________________________________________________________________
 
@JsonCreator 


The @JsonCreator annotation can be used on constructors or factory methods for mapping incoming JSON properties to the constructor/factory method arguments. This annotation is used only during deserialization and can be particularly useful for immutable objects




Comments

Popular posts from this blog

The BattleGround

Last Sunday while zapping the channels of my idiot box I chanced upon to watch one of the greatest epic of our times –MAHABHARAT. It did’nt take me much time to recall the waves that it created across the nation- when it was telecasted for the first time.I was too young to comprehend it,yet I used to watch it with paramount interest,sitting next to dad & imitating his stimuli to what character speaks Later in my teens ,unlike most of my friends who used to enjoy watching top tens & horror shows , I was inundated to discover that zee was going to re telecast Mahabharat .This time, I was grown up enough to understand it,so I religiously watched all the episodes with same interest. Watching such an epic in formative years has great influence on one’s approach towards life .Today to me ,Mahabharat isn’t just another epic but it is a thinking process, where the mind is the battleground, THE KURUSHETRA ,where all kind of thoughts hover, the state of mind that we...

WHERE THE MIND IS WITHOUT FEAR !

(Painting By Takshila Vidushi) "Where the mind is without fear & the head is held high Where knowledge is free Where the world hasn't been broken up into fragments By narrow domestic walls Where words come out from the depth of truth Where tireless striving stretches its arms towards perfection ! Where the clear stream of reason has not lost its way Into the dreary desert sand of dead habit Where the mind is led forward by thee Into ever-widening thought and action Into that heaven of freedom, my Father, let my country awake." By Guru RabindraNath Tagore (Ever since childhood this poem of RabindraNath Tagore has been synonmous to supreme level of perfection for me.Its incredibl...

GraphQL

What is GraphQL  API Standard invented & open-sourced by Facebook Alternative to  REST API  enables declarative data fetching  exposes single endpoint & responds to queries How it works?  Why Graphql? Improvises performance by reducing the data that is to be transferred over the internet Variety of different frontend frameworks and platforms on client-side Fast development speed & expectation for rapid feature development Why Graphql is better than REST? Flexibility & efficient  No more over /under fetching of data Over fetching : Under fetching: Insightful analytics  Schema serves as contract between client and server CORE CONCEPTS : SDL :SCHEMA DEFINITION LANGUAGE Writing Data with mutations 3 kinds of mutations creating new data updating existing data deleting existing data