When to Use @JsonValue Annotation Using Jackson in Java



In Java, Jackson is a library that is used to convert JSON to Java objects and vice versa. Jackson Annotations are used during serialization and deserialization.

  • We use these to denote or specify annotations before a particular field or method (that is declared in Java).
  • Using an annotation before a field, we can denote whether it is a variable, is a JsonProperty, should be ignored, or what condition should be applied to it.

So basically, Annotations make JSON output clearer as we required. In this Article, we will learn about one of its annotations is @JsonValue Annotation.

The @JsonValue Annotation

The @JsonValue Annotation indicates which method/field should be used to serialize the entire object as a single value.

It means when Jackson serializes an object, instead of including all its properties in JSON output, it will include only the value returned by the method having the annotation @JsonValue.

Syntax

Following is the usage of the @JsonValue Annotation -

//Method to be included
@JsonValue
public String getName() {
   return code;
}
//This will not be included in the output 
public String getAge() {
   return name;
}

Example

In the given program, @JsonValue annotation is used to serialize a Currency "code" object as a single string, instead of a full JSON object. As a result, when serialized using Jackson, an instance like Currency will output only the given annotation rather than other properties of the currency.

import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonValueExample {
   public static void main(String[] args) throws Exception {
      ObjectMapper mapper = new ObjectMapper();

      // Create and serialize a Currency object
      Currency usd = new Currency("USD", "US Dollar", 1.0);
      String jsonString = mapper.writeValueAsString(usd);

      System.out.println(jsonString);
   }
}

class Currency {
   private String code;
   private String name;
   private double rate;

   public Currency(String code, String name, double rate) {
      this.code = code;
      this.name = name;
      this.rate = rate;
   }

   //  represent the entire object
   @JsonValue
   public String getCode() {
      return code;
   }

   public String getName() {
      return name;
   }

   public double getRate() {
      return rate;
   }
}

Following is the output of the @JsonValue Annotation -

"USD"

Let's also see the output without using @JsonValue Annotation -

{"code":"USD","name":"US Dollar","rate":1.0}
Updated on: 2025-05-19T16:23:29+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements