gpt4 book ai didi

java - 如何使用 Jackson 将 JSON 属性按前缀映射/分组到对象列表?

转载 作者:行者123 更新时间:2023-11-30 05:46:54 25 4
gpt4 key购买 nike

我有 JSON 响应:

{
"part1.id": "1",
"part1.name": "Name1",
"part2.id": "2",
"part2.name": "Name2"
}

1 个用户的 POJO/DTO 类:

public class User {

private String id;
private String name;

// set/get
}

以及整个响应的类:

public class UsersResponse {

private List<User> users;

// set/get
}

我可以检索 Map 中的值,然后手动解析/映射代码,就像 Jackson JSON map key as property of contained object

还有@JsonAlias用于多种命名变体,但它映射到一个对象。

是否有其他方法可以将 JSON 值映射/分组到提供的前缀列表?

最佳答案

没有已实现的注释允许通过配置来完成此操作。您需要实现反序列化器。解串器的简单版本如下所示:

class UsersResponseDeserializer extends JsonDeserializer<UsersResponse> {

private Pattern propertyPattern = Pattern.compile("^part(\\d+)\\.(.+)$");

@Override
public UsersResponse deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
Integer lastIndex = null;
String lastName = null;
Map<Integer, Map<String, String>> users = new LinkedHashMap<>();
while (p.currentToken() != null) {
switch (p.currentToken()) {
case FIELD_NAME:
String name = p.getText();
Matcher matcher = propertyPattern.matcher(name);
if (matcher.matches()) {
lastIndex = Integer.parseInt(matcher.group(1));
lastName = matcher.group(2);
}
break;
case VALUE_STRING:
if (lastIndex != null && lastName != null) {
Map<String, String> user = users.computeIfAbsent(lastIndex, k -> new HashMap<>());
user.put(lastName, p.getValueAsString());
lastIndex = null;
lastName = null;
}
break;
default:
break;
}
p.nextToken();
}

UsersResponse response = new UsersResponse();
response.setUsers(users);

return response;
}
}

我改变了一点UsersResponse如下所示:

@JsonDeserialize(using = UsersResponseDeserializer.class)
class UsersResponse {

private Map<Integer, Map<String, String>> users;

public Map<Integer, Map<String, String>> getUsers() {
return users;
}

public void setUsers(Map<Integer, Map<String, String>> users) {
this.users = users;
}

@Override
public String toString() {
return "UsersResponse{" +
"users=" + users +
'}';
}
}

使用示例:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.type.CollectionLikeType;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonApp {

public static void main(String[] args) throws Exception {
File jsonFile = new File("path to json").getAbsoluteFile();


ObjectMapper mapper = new ObjectMapper();
UsersResponse data = mapper.readValue(jsonFile, UsersResponse.class);
System.out.println(data);
CollectionLikeType usersListType = mapper.getTypeFactory().constructCollectionLikeType(List.class, User.class);
List<User> users = mapper.convertValue(data.getUsers().values(), usersListType);
System.out.println(users);
}
}

给定的 Abobe 应用程序 JSON :

{
"part1.id": "1",
"part1.name": "Name1",
"part2.id": "2",
"part2.name": "Name2",
"part33.id": "33",
"part33.name": "Name33"
}

打印:

UsersResponse{users={1={name=Name1, id=1}, 2={name=Name2, id=2}, 33={name=Name33, id=33}}}
[User{id='1', name='Name1'}, User{id='2', name='Name2'}, User{id='33', name='Name33'}]

在解串器中我使用了 Map<Integer, Map<String, String>>因为我不想玩匹配 POJO propertiesJSON键。

关于java - 如何使用 Jackson 将 JSON 属性按前缀映射/分组到对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54674805/

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