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

Microservices Design patterns

What are microservices? Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are Highly maintainable and testable Loosely coupled Independently deployable Organized around business capabilities Owned by a small team The microservice architecture enables the rapid, frequent and reliable delivery of large, complex applications. It also enables an organization to evolve its technology stack. You are developing a server-side enterprise application. It must support a variety of different clients including desktop browsers, mobile browsers and native mobile applications. The application might also expose an API for 3rd parties to consume. It might also integrate with other applications via either web services or a message broker. The application handles requests (HTTP requests and messages) by executing business logic; accessing a database; exchanging messages with other systems; and returni...

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