英文:
How to deserialize a List of String to a single arg value class?
问题
@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; } }
英文:
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
> java
> @lombok.Value
> public class MyId {
> @JsonValue
> String id;
>
> public MyId(final String id) {
> this.id = id;
> }
> }
>
答案1
得分: 1
你可以使用 @JsonValue
。从文档中可以得知:
标记注解,指示被注解的访问器(可以是字段或“getter”方法[一个具有非void返回类型且无参数的方法])的值将用作实例序列化的单个值,而不是通常的收集值属性的方法。通常值将是简单标量类型(String或Number),但它可以是任何可序列化类型(Collection、Map或Bean)。
用法:
@Value
public class MyId {
@JsonValue
String id;
}
完整代码:
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;
}
输出:
{
"ids": [
"one",
"two"
],
"otherField": "some other field value"
}
英文:
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"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论