Reputation: 13
Basically I always want to unwrap my Id class to the parent object but in case of a List<> I can not use the JsonUnwrapped Annotation from the jackson library.
@lombok.Value
public class Response {
List<MyId> ids;
// ... other fields
}
@lombok.Value
public class MyId {
String id;
}
{
"ids": ["id1", "id2"]
"otherField": {}
}
Working solution with jackson-databind 2.11
@lombok.Value public class MyId { @JsonValue String id; public MyId(final String id) { this.id = id; } }
Upvotes: 0
Views: 199
Reputation: 4088
You can use @JsonValue
. From docs:
Marker annotation that indicates that the value of annotated accessor (either field or "getter" method [a method with non-void return type, no args]) is to be used as the single value to serialize for the instance, instead of the usual method of collecting properties of value. Usually value will be of a simple scalar type (String or Number), but it can be any serializable type (Collection, Map or Bean).
Usage:
@Value
public class MyId {
@JsonValue
String id;
}
Complete code:
public class JacksonExample {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
List<MyId> myIds = new ArrayList<>();
MyId id1 = new MyId("one");
MyId id2 = new MyId("two");
myIds.add(id1);
myIds.add(id2);
Response response = new Response(myIds, "some other field value");
System.out.println(objectMapper.writeValueAsString(response));
}
}
@Value
class Response {
List<MyId> ids;
String otherField;
}
@Value
class MyId {
@JsonValue
String id;
}
Output:
{
"ids": [
"one",
"two"
],
"otherField": "some other field value"
}
Upvotes: 1