gpt4 book ai didi

java - 如何根据json属性前缀在jackson中创建数组字段?

转载 作者:行者123 更新时间:2023-11-30 02:43:18 25 4
gpt4 key购买 nike

假设我有以下 json 字符串:

{
"name": "Foo"
"pic1": "some pic 1",
"pic2": "some pic 2",
"pic3": "some pic 3",
...
"picn": "some pic n"
}

我需要创建以下 POJO:

class Foo {
String name;
String[] pics;
}

来自该字符串。

诀窍是我需要以某种方式将 pic* 映射到 String[] 图片。

我如何使用 Jackson 来做到这一点?

最佳答案

添加您自己的自定义序列化器和反序列化器。

@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeSerializer.class)
public class Foo {
private String name;
private String[] pics;

序列化器:

public class MySerializer extends JsonSerializer<Foo> {

@Override
public void serialize(Foo value, JsonGenerator jgen, SerializerProvider serializers) throws IOException {
int i = 1;
String fieldName = "pics";
jgen.writeStartObject();
jgen.writeStringField("name", value.getName());
for (String stringValue : value.getPics()) {
jgen.writeStringField(fieldName + i, stringValue);
i++;
}
jgen.writeEndObject();

}

}

解串器:

public class MyDeSerializer extends JsonDeserializer<Foo> {

@Override
public Foo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec objectCodec = jp.getCodec();
Foo foo = new Foo();
JsonNode node = objectCodec.readTree(jp);

Iterator<Entry<String, JsonNode>> fields = node.fields();
String[] pics = new String[node.size() - 1];

int i = 0;
while (fields.hasNext()) {
Entry<String, JsonNode> next = fields.next();
if (next.getKey().equalsIgnoreCase("name"))
foo.setName(node.get("name").asText());
else {
pics[i] = node.get(next.getKey()).asText();
i++;
}
}
foo.setPics(pics);
return foo;
}
}

关于java - 如何根据json属性前缀在jackson中创建数组字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41003798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com