gpt4 book ai didi

java - Jackson:反序列化时保留对映射值中键的引用

转载 作者:行者123 更新时间:2023-12-03 19:39:07 25 4
gpt4 key购买 nike

我有以下 JSON,其中包含从用户 ID 到用户详细信息的映射:

{
"users": {
"john": { "firstName": "John", "lastName": "Doe" },
"mark": { "firstName": "Mark", "lastName": "Smith" }
}
}

我正在使用以下代码将 JSON 反序列化为 Java 对象:
class User {
public String userID;

public String firstName;
public String lastName;
}

public class Users {
public Map<String, User> users;

public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Reader source = Files.newBufferedReader(Paths.get("test.json"));
Users all = mapper.readValue(source, Users.class);
// ...
}
}

反序列化后,我想要字段 User.userID设置为 users中对应的key map 。

例如 all.users.get("john").userID应该是 "john" .

我怎样才能做到这一点?

最佳答案

为 User 对象创建一个自定义反序列化器,并将其用于 Map。这是一个完整的例子:

@Test
public void test() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();

Data data = mapper.readValue("{\"users\": {\"John\": {\"id\": 20}, \"Pete\": {\"id\": 30}}}", Data.class);

assertEquals(20, data.users.get("John").id);
assertEquals(30, data.users.get("Pete").id);
assertEquals("John", data.users.get("John").name);
assertEquals("Pete", data.users.get("Pete").name);
}

public static class Data {
@JsonDeserialize(contentUsing = Deser.class)
public Map<String, User> users;
}

public static class User {
public String name;
public int id;
}

public static class Deser extends JsonDeserializer<User> {

@Override
public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String name = ctxt.getParser().getCurrentName();

User user = p.readValueAs(User.class);

user.name = name; // This copies the key name to the user object

return user;
}
}

关于java - Jackson:反序列化时保留对映射值中键的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763298/

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