我有一个具有以下值的字符串:
{
"keyA": {
"ID": "123",
"Name": "TESTA",
"Mobile": "1111"
},
"keyB": {
"ID": "456",
"Name": "TESTB",
"Mobile": "2222"
}
}
如何将json转换为列表和类格式
我想将它解析为List
请告知如何使用Jackson ObjectMapper?
答案 0 :(得分:1)
您可以尝试进行测试:
public static void main(String[] args) {
String jsonString = "{\n" +
" \"keyA\": {\n" +
" \"ID\": \"123\",\n" +
" \"Name\": \"TESTA\",\n" +
" \"Mobile\": \"1111\"\n" +
" },\n" +
" \"keyB\": {\n" +
" \"ID\": \"456\",\n" +
" \"Name\": \"TESTB\",\n" +
" \"Mobile\": \"2222\"\n" +
" }\n" +
"}";
List<CustomObject> customObjects = new ArrayList<CustomObject>();
ObjectMapper mapper = new ObjectMapper();
try {
ClassA myClassAObject= mapper.readValue(jsonString, ClassA.class);
customObjects.add(myClassAObject.getKeyA());
customObjects.add(myClassAObject.getKeyB());
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println(customObjects.size());
}
我的其他模特课CustomObject
:
public class CustomObject {
private String id;
private String name;
private String mobile;
@JsonProperty("ID")
public String getId() {
return id;
}
@JsonProperty("ID")
public void setId(String id) {
this.id = id;
}
@JsonProperty("Name")
public String getName() {
return name;
}
@JsonProperty("Name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("Mobile")
public String getMobile() {
return mobile;
}
@JsonProperty("Mobile")
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
和ClassA
public class ClassA {
private CustomObject keyA;
private CustomObject keyB;
public CustomObject getKeyA() {
return keyA;
}
public void setKeyA(CustomObject keyA) {
this.keyA = keyA;
}
public CustomObject getKeyB() {
return keyB;
}
public void setKeyB(CustomObject keyB) {
this.keyB = keyB;
}
}
如果您遇到问题,这是我在Maven
中使用的库版本:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>