javajsonjacksonfasterxml

Ignore property when converting object to json string but not when converting string to Object using by Jackson library


I have a REST API that provides me a JSON. In the json I receive from the REST API, there is a ID property I want to read so I can do some checking on it. However, when I want to write back to the web server, the ID property must not be present in the response JSON string. So it has to be a write-only property, but simply changing a property to write-only prevents be to check what the value is of that property.

For example, I create a new product:

public class Product {
    
    //This feild should not be ignore when I convert JSON to object. 
    // But the same one should be ignore when I convert the object to Json
    @JsonProperty
    public String id;
    
    @JsonProperty
    public String name;
   
}

GET response:

{
  "id": 1,
  "name": "Product1"
}

POST Wrong:

{
  "id": 1, <-- This should be in the response
  "name": "Product1"
}

POST should be:

{
  "name": "Product1"
}

Solution

  • To prevent a certain field from being serialized, you can use access attribute of the @JsonProperty annotation by assigning it to JsonProperty.Access.WRITE_ONLY.

    public static class Product {
        @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
        public String id;
        public String name;
        
        // getters, setters
    }
    

    Usage example:

    String incomingJson = """
        {
            "id": 1,
            "name": "Product1"
        }
        """;
            
    Product product = mapper.readValue(incomingJson, Product.class);
    String result = mapper.writeValueAsString(product);
    System.out.println(result);
    

    Output:

    {"name":"Product1"}