uncle bob
uncle bob

Reputation: 680

Can i parse to JSON with non-defining property automatically?

I'm currently using jackson to serialize/deserialize my object:

public class Person {
  private String firstName;
  private String lastName;
  //getter & setter
}

after deserializing, Json string will look like this:

{ 
  "person" : {
              "firstName": "john",
              "lastName" :  "doe"
              }
 }

Now i want to have one more field, it's fullname and it's combining from firstname and lastname. So JSON will look like this

{ 
      "person" : {
                  "firstName": "john",
                  "lastName" :  "doe",
                  "fullName" : "john doe"
                  }
     }

I can do that by add more property to class Person but i don't like it much, Is there any annotation provided by Jackson can support this case automatically? That my Person class is still the same (maybe add more method but not property) and Json string afterward contain some additional data.

Thanks

Upvotes: 1

Views: 37

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

Jackson will (by default) look for getters in a class to decide what to serialize in JSON. You can add a getter method on Person to add extra fields you want in JSON, regardless of the fields in Person class:

public String getFullName() {
    return firstName + " " + lastName;
}

The name of the field in JSON will be appear as "fullName" according to Java Beans conventions.

Upvotes: 3

Related Questions