Thursday, May 2, 2024
HomeJavaThe right way to use @JsonCreator and @JsonPropertOrder Jackson JN Annotation in...

The right way to use @JsonCreator and @JsonPropertOrder Jackson JN Annotation in Java? Examples


annotation, let me briefly inform you a bit extra about what Java actually is.  For these of you who do not know, Java is mainly a general-purpose, class-based, object-oriented programming language that goals to have lesser implementation dependencies. You too can consider Java as a computing platform for software improvement. What units Java aside is that it’s quick, safe, and dependable. It may be used for growing Java functions with the assistance of laptops, knowledge facilities, sport consoles, scientific supercomputers, and even cell telephones.

The right way to Use The @JsonCreator Annotation Alongside With Examples

A
Java platform is mainly a group of applications that may enable you to
develop and run Java programming functions. It’s made up of an
execution engine, a compiler, and a set of libraries. It’s mainly a
set of pc software program and specs. 

Java was developed by James Gosling when he was working at Solar Microsystems. It was later acquired by the Oracle Company. 

Java
can be used for growing android functions, creating
Enterprise Software program, creating cell java functions, creating
scientific computing functions, Huge Information analytics, programming
{hardware} units, and server-side applied sciences like Apache and
GlassFish.

In quite simple phrases, @JsonCreator can be utilized for
fine-tuning the constructors or the manufacturing facility strategies which can be utilized in
deserialization. Additionally, you will be capable of obtain comparable outcomes by
utilizing the @JsonProperty annotation. On this article, I’ll present you ways
you possibly can match JSON with a unique format for a particular class. This
will be carried out by defining the required property names.

@JsonCreator Jackson Annotation Instance in Java

Right here is our full Java program you possibly can run to find out how @JsonCreator annotation work and you should use to create object from JSON configuration or JSON recordsdata

import java.io.IOException; 

import java.textual content.ParseException; 



import com.fasterxml.jackson.annotation.JsonCreator; 

import com.fasterxml.jackson.annotation.JsonProperty; 

import com.fasterxml.jackson.databind.ObjectMapper; 



public class JacksonTester {

   public static void primary(String args[]) throws ParseException{ 

      String json = "{"id":1,"theName":"Mark"}"; 

      ObjectMapper mapper = new ObjectMapper();    

      strive {

         Scholar scholar = mapper 

            .readerFor(Scholar.class) 

            .readValue(json); 

         System.out.println(scholar.rollNo +", " + scholar.title); 

      }

      catch (IOException e) { 

         e.printStackTrace(); 

      }

   }

}

class Scholar {

   public String title; 

   public int rollNo; 


   @JsonCreator 

   public Scholar(@JsonProperty("theName") String title, @JsonProperty("id") int rollNo){

      this.title = title; 

      this.rollNo = rollNo; 

   }

}

Output

Should you run this program, you’re going to get the next output:

1, Mark 

How to use @JsonCreator and @JsonPropertOrder Jackson JN Annotation in Java? Examples

Now, allow us to see one other instance. Allow us to think about that you simply wish to serialize the next JSON:

{
    "id":1,

    "theName":"My bean"
}

You are able to do this through the use of both the @JsonCreator annotation or the @JsonProperty annotation. See the next instance:

public class BeanWithCreator {

    public int id;

    public String title;



    @JsonCreator

    public BeanWithCreator(

      @JsonProperty("id") int id, 

      @JsonProperty("theName") String title) {

        this.id = id;

        this.title = title;

    }

}



@Check

public void whenDeserializingUsingJsonCreator_thenCorrect()

  throws IOException {

 

    String json = "{"id":1,"theName":"My bean"}";



    BeanWithCreator bean = new ObjectMapper()

      .readerFor(BeanWithCreator.class)

      .readValue(json);

    assertEquals("My bean", bean.title);

}

In
addition to @JsonCreator, there are a number of different Jackson annotations
that may make your programming simpler. Allow us to take a look at a couple of of them.

The
@JsonAnyGetter annotation gives you the pliability of utilizing a Map
area similar to commonplace properties. Take a look at the next instance:

public class ExtendableBean {

    public String title;

    non-public Map<String, String> properties;



    @JsonAnyGetter

    public Map<String, String> getProperties() {

        return properties;

    }

}



{

    "title":"My bean",

    "attr2":"val2",

    "attr1":"val1"

}



@Check

public void whenSerializingUsingJsonAnyGetter_thenCorrect()

  throws JsonProcessingException {


    ExtendableBean bean = new ExtendableBean("My bean");

    bean.add("attr1", "val1");

    bean.add("attr2", "val2");


    String outcome = new ObjectMapper().writeValueAsString(bean);


    assertThat(outcome, containsString("attr1"));

    assertThat(outcome, containsString("val1"));

}

The
@JsonGetter annotation can act as an environment friendly different for the
@JsonProperty annotation. See the next instance to get a greater
understanding:

public class MyBean {

    public int id;

    non-public String title;



    @JsonGetter("title")

    public String getTheName() {

        return title;

    }

}



@Check

public void whenSerializingUsingJsonGetter_thenCorrect()

  throws JsonProcessingException {

 
    MyBean bean = new MyBean(1, "My bean");


    String outcome = new ObjectMapper().writeValueAsString(bean);


    assertThat(outcome, containsString("My bean"));

    assertThat(outcome, containsString("1"));

}

As
the title suggests, the @JsonPropertOrder annotation can be utilized for
specifying the order of properties with regard to serialization. See the
following instance:

@JsonPropertyOrder({ "title", "id" })

public class MyBean {

    public int id;

    public String title;

}

You’re going to get an output like this:

{

    "title":"My bean",

    "id":1

}

Now we will run a easy take a look at:

@Check

public void whenSerializingUsingJsonPropertyOrder_thenCorrect()

  throws JsonProcessingException {


    MyBean bean = new MyBean(1, "My bean");


    String outcome = new ObjectMapper().writeValueAsString(bean);

    assertThat(outcome, containsString("My bean"));

    assertThat(outcome, containsString("1"));

}

The serialization output might be like this:

{

    "id":1,

    "title":"My bean"

}

You
may also use the @JsoRawValue annotation for ordering Jackson to serialize a
property precisely as it’s. Take a look at the next instance:

public class RawBean {

    public String title;


    @JsonRawValue

    public String json;

}

The output of serializing might be like this:

{

    "title":"My bean",

    "json":{

        "attr":false

    }

}

Subsequent, we are going to run a easy take a look at:

@Check

public void whenSerializingUsingJsonRawValue_thenCorrect()

  throws JsonProcessingException {


    RawBean bean = new RawBean("My bean", "{"attr":false}");


    String outcome = new ObjectMapper().writeValueAsString(bean);

    assertThat(outcome, containsString("My bean"));

    assertThat(outcome, containsString("{"attr":false}"));

}

The
@JsonValue annotation can be utilized for indicating a particular technique that
can be utilized by the library for serializing the entire occasion. See the
following instance to realize a greater understanding:

public enum TypeEnumWithValue {

    TYPE1(1, "Kind A"), TYPE2(2, "Kind 2");



    non-public Integer id;

    non-public String title;



    // commonplace constructors



    @JsonValue

    public String getName() {

        return title;

    }

}



@Check

public void whenSerializingUsingJsonValue_thenCorrect()

  throws JsonParseException, IOException {

 
    String enumAsString = new ObjectMapper()

      .writeValueAsString(TypeEnumWithValue.TYPE1);



    assertThat(enumAsString, is(""Kind A""));

}

If
wrapping is enabled, the @JsonRootName annotation can be utilized for
specifying the title of the basis wrapper that’s for use. Take a look at
the given instance:

{

    "id": 1,

    "title": "John"

}

Whether it is wrapped, it’ll most likely appear like this:

{

    "Consumer": {

        "id": 1,

        "title": "John"

    }

}

Now, see this instance:

@JsonRootName(worth = "person")

public class UserWithRoot {

    public int id;

    public String title;

}



@Check

public void whenSerializingUsingJsonRootName_thenCorrect()

  throws JsonProcessingException {

 

    UserWithRoot person = new Consumer(1, "John");



    ObjectMapper mapper = new ObjectMapper();

    mapper.allow(SerializationFeature.WRAP_ROOT_VALUE);

    String outcome = mapper.writeValueAsString(person);



    assertThat(outcome, containsString("John"));

    assertThat(outcome, containsString("person"));

}

The output of the serialization might be like this:

{

    “person”:{

        “id”:1,

        “title”:”John”

    }

}

That is all about tips on how to use Jackson annotations to serialize and deserialize JSON in Java. We’ve got seen examples of @JsonCreator, @JsonPropertOrder, @JSonValue, and plenty of different helpful Jackson annotation in Java. 

If
you preferred this text on tips on how to use the @JsonCreator annotation, really feel
free to share it along with your family and friends. I’ve little doubt that the
interfaces on this checklist will rework you from a whole newbie to a
Java professional inside a matter of weeks or months. 

There are a large
number of examples on this checklist that might be helpful to each
absolute newcomers in addition to intermediate-level learners. 

You too can drop a remark when you have any doubts and we are going to get again to you as quickly as doable. 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments