skip to Main Content

I have a POJO like this:

public class Person {
  public long id;
  public String someOtherId;
  public String vollName;
  public int alter;
}

I am converting the POJO to JSON using the mixin:

@JsonIncludeProperties( { "id", "name", "age", "customFields" } )
abstract class PersonM extends Person {
  @JsonProperty( "id" ) String someOtherId;
  @JsonProperty( "name" ) String vollName;
  @JsonProperty( "age" ) String alter;
}

...

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn( Person.class, PersonM.class );
String body = mapper.writeValueAsString( person );

The code works like charm and produces a JSON of:

{
  "id": "xxxxxx",
  "name": "Aaaa Bbbb",
  "age": 111
}

Now I need to extend the JSON to contain a customFields element:

{
  "id": "xxxxxx",
  "name": "Aaaa Bbbb",
  "age": 111,
  "customFields": {
    "originalId": 333333
  }
}

so that the content of that new element is based on other fields of the same POJO, and would look like so as a getter:

public class Person {
 ...
 public Map getCustomFields() { return Map.of( "originalId", id ); }
}

I don’t want to include this or similar methods into my POJO for a number of reasons and would like to do it on StdSerializer<>-level.

On the Internet I could not find any example on adding another JSON element to the existing fields, all samples show building JSON from scratch instead.

Hence the question: How to add a JSON Object to existing output without "re-inventing the wheel" over and over again?

2

Answers


  1. create a custom PersonDeserializer by extending JsonDeserializer. Inside the deserialize method, we extract the id, name, and age values from the JSON node. Then, we create a Person object and set its properties accordingly. Additionally, we create a customFields map and populate it with the desired custom field values. Finally, we set the customFields map on the Person object.

    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.JsonDeserializer;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    public class PersonDeserializer extends JsonDeserializer<Person> {
    
        @Override
        public Person deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            ObjectNode node = jsonParser.getCodec().readTree(jsonParser);
            long id = node.get("id").asLong();
            String name = node.get("name").asText();
            int age = node.get("age").asInt();
    
            Person person = new Person();
            person.setId(id);
            person.setName(name);
            person.setAge(age);
    
            Map<String, Object> customFields = new HashMap<>();
            customFields.put("originalId", id);
            person.setCustomFields(customFields);
    
            return person;
        }
    }
    

    To use this custom deserializer, you need to register it with the ObjectMapper:

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Person.class, new PersonDeserializer());
    mapper.registerModule(module);
    
    String json = mapper.writeValueAsString(person);
    

    or try this :

      class Person {
                public long id;
                public String someOtherId;
                public String vollName;
                public int alter;
            }
    
            // Create an instance of the original POJO
            Person person = new Person();
            person.id = 123;
            person.someOtherId = "abc";
            person.vollName = "John Doe";
            person.alter = 30;
    
            // Create a custom map for additional properties
            Map<String, Object> additionalProperties = new HashMap<>();
            additionalProperties.put("originalId", 333333);
    
            // Create an instance of the ObjectMapper
            ObjectMapper mapper = new ObjectMapper();
    
            // Convert the POJO to JSON
            String json = mapper.writeValueAsString(person);
    
            // Merge the additional properties with the original JSON
            String mergedJson = mergeJson(json, additionalProperties);
            System.out.println(mergedJson);
        }
    
        private static String mergeJson(String originalJson, Map<String, Object> additionalProperties) throws Exception {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> mergedProperties = mapper.readValue(originalJson, Map.class);
    
            // Merge the additional properties with the original properties
            mergedProperties.putAll(additionalProperties);
            return mapper.writeValueAsString(mergedProperties);
        }
    
    Login or Signup to reply.
  2. You can add elements to your json, your only need convert from String, did you try this?

    ObjectNode json=(ObjectNode) mapper.readTree(body);
    json.set("CustomFields", mapper.valueToTree(Map.of( "originalId", person.getId())));
    body=json.toString();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search