1

I have a json string and I want to do some changes to it with the following code in Java using Jackson:

public String transformJson(String json) {

    final ObjectMapper mapper = new ObjectMapper();

    Student s = mapper.readValue(json, Student.class))

    // Do some changes on the object s

    return mapper.writeValueAsString(s);
}

Here is the Student class:

@AllArgsConstructor
@Data
@JsonInclude(Include.NON_NULL)
public static class Student {
    private String firstName;
    private String lastName;
    private String country;
    private Long age;
}

The code above works and let's suppose the json in input is the following:

{
   "firstName" : "Jim",
   "lastName" : "Miles"
}

If no change is done, the output would be the same. The annotation @JsonInclude(Include.NON_NULL) would just remove any null field from the output.

But now the new requirement is this: when the input json explicity define a value as null, then the output should show that field as null. That means that when the input is the following:

{
   "firstName" : "Jim",
   "lastName" : "Miles",
   "country" : null 
}

Then the output should still be:

{
   "firstName" : "Jim",
   "lastName" : "Miles",
   "country" : null 
}

Any idea on how I can achieve this?

2
  • You could try wrapping all your fields in AtomicReference, but that's not really elegant. What's the point in having the property with value null? What's the difference between {country: null} and {}? Commented Nov 17, 2020 at 17:37
  • When you need to transform JSON->JSON, sometimes you may find useful to don't use an intermediate object representation at all. See, for example: stackoverflow.com/questions/64422516/… Commented Nov 18, 2020 at 7:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.