gpt4 book ai didi

java - 如何将以下 JSON 字符串转换为 POJO

转载 作者:搜寻专家 更新时间:2023-11-01 01:40:51 25 4
gpt4 key购买 nike

我想将以下 JSON 字符串转换为 Java 对象:

{
"user": {
"0": {
"firstName": "Monica",
"lastName": "Belluci"
},
"1": {
"firstName": "John",
"lastName": "Smith"
},
"2": {
"firstName": "Owen",
"lastName": "Hargreaves"
}
}
}

为了将其转换为 Java 对象,我创建了以下类:

class User {
private Map<String, MyObject> user = new HashMap<>();
//Getter and Setter is here
}

class MyObject {
private String firstName;
private String lastName;
//Getters and Setters are here
}

我正在使用 Jackson 库将 JSON 转换为 Java。以下是我如何使用 Jackson 进行转换:

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class);

问题是,通过上面的这种转换,User 对象中的 Map 始终为空。我做错了什么?

提前致谢。

最佳答案

我认为它应该有效。我已经执行了这段代码并且运行良好。这是我的例子。

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class TestJackson {

public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String testJson = "{\n" + " \"user\": {\n" + " \"0\": {\n" + " \"firstName\": \"Monica\",\n" + " \"lastName\": \"Belluci\"\n" + " },\n" + " \"1\": {\n" + " \"firstName\": \"John\",\n" + " \"lastName\": \"Smith\"\n" + " },\n" + " \"2\": {\n" + " \"firstName\": \"Owen\",\n" + " \"lastName\": \"Hargreaves\"\n" + " }\n" + " }\n" + "}";
User readValue = mapper.readValue(testJson, User.class);
System.out.println("readValue = " + readValue);
}
}

和用户类:

import java.util.HashMap;
import java.util.Map;

class User {
private Map<String, MyObject> user = new HashMap<String, MyObject>();

public Map<String, MyObject> getUser() {
return user;
}

public void setUser(Map<String, MyObject> user) {
this.user = user;
}

@Override
public String toString() {
return "User{" +
"user=" + user +
'}';
}
}

class MyObject {
private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

@Override
public String toString() {
return "MyObject{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}

关于java - 如何将以下 JSON 字符串转换为 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41499935/

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