gpt4 book ai didi

java - ObjectMapper 从具有特定名称的字段创建列表

转载 作者:行者123 更新时间:2023-11-30 06:47:06 26 4
gpt4 key购买 nike

我有一个 JSON,我将其解析为结果对象列表。此对象包含 5 个字符串字段,称为 photo1、photo2 等。(基于 JSON)是否可以将它们直接读入列表字段?

JSON 喜欢:

{
"ErrorMessage": null,
"Result": [{
"id": "462290",
"name_English": "name in english",
"name_Local": "külföldiül a név",
"zipcode": "5463",
"photo1": "dfglkj.com/blabla",
"photo2": "dfglkj.com/blabla",
"photo3": "dfglkj.com/blabla",
"photo4": "dfglkj.com/blabla",
"photo5": "dfglkj.com/blabla"
}]
}

和我的对象:

static final class ApiResponse
{
public String ErrorMessage;
public List<Result> Result = new ArrayList<Result>();
}

static final class Result
{
public String id;
public String name_English;
public String name_Local;
public List<String> photos;
public String zipcode;
}

我有一个 ObjectMapper:

private static ObjectMapper newObjectMapper()
{
final ObjectMapper om =
new ObjectMapper() //
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false) //
.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);

om.registerSubtypes(ApiResponse.class);

return om;
}

在解析器中:

final ApiResponse ret = OM.readValue(inputStream, ApiResponse.class);

最佳答案

根据 Gaetano 的回答,我写了一个更通用的解决方案(任意数量的照片,任意数量的其他字段

@Override public List<Result> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
JsonNode node = jp.getCodec().readTree(jp);
List<Result> listResult = new ArrayList<Result>();

for (JsonNode interNode : node)
{
Result result = new Result();

for (int i = 1; i < 30; i++)
{
if (interNode.get("photo" + i) != null)
{
result.photos.add(interNode.get("photo" + i).getTextValue());
}
else
{
break;
}
}

for (Field field : result.getClass().getDeclaredFields())
{
if (interNode.get(field.getName()) != null)
{
try
{
field.set(result, interNode.get(field.getName()).getTextValue());
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}

listResult.add(result);
}

return listResult;
}

关于java - ObjectMapper 从具有特定名称的字段创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562089/

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