java试图从json映射到包含对象的域模型
我有一个Json:
"{\"userID\":2,\"title\":\"jfsdk\",\"content\":\"dskljf\",\"tagList\":{\"name\":\"fysikk\",\"name\":\"Matte\",\"name\":\"Kjemi\"}}"
我想解析为一个域模型类
public class ThreadCreatingModel {
int userID;
String title;
String content;
ArrayList<Tag> tagList;
public ThreadCreatingModel(){}
public ThreadCreatingModel(int userID, String title, String content, ArrayList<Tag> tagList) {
this.userID = userID;
this.title = title;
this.content = content;
this.tagList = tagList;
}
@JsonProperty("userID")
public int getUserID() { return this.userID; }
public void setUserID(int userID) { this.userID = userID; }
@JsonProperty("title")
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
@JsonProperty("content")
public String getContent() { return this.content; }
public void setContent(String content) { this.content = content; }
public ArrayList<Tag> getTagList() { return this.tagList; }
public void setTagList(ArrayList<Tag> tagList) { this.tagList = tagList;}
其中还包含一个标记类:
public class Tag {
public String name;
public Tag(){
}
public Tag(String name) {
this.name = name;
}
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
}
在mapper类中,我执行以下操作:
String incoming = "{\"userID\":2,\"title\":\"jfsdk\",\"content\":\"dskljf\",\"tagList\":{\"name\":\"fysikk\",\"name\":\"Matte\",\"name\":\"Kjemi\"}}";
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true);
ThreadCreatingModel tcm = null;
try {
tcm = mapper.readValue(incoming, ThreadCreatingModel.class);
System.out.println(tcm.getTagList().get(0).name);
} catch (IOException ioe) {
System.out.println(ioe.toString());
System.out.println("Failed mapping");
}
}
当我有“get(0)”时,我只得到最后一个。
如果我试着放1,我会得到一个
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
如果我移除
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true)
我得到这个错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: java.io.StringReader@66cc75ad; line: 1, column: 47] (through reference chain: com.accenture.studass.domain.ThreadCreatingModel["tagList"])
有什么帮助吗?已经谷歌搜索很久了
# 1 楼答案
我重新设计了我的前端代码,因此我的JSON看起来像这样,正如MichałZiober提到的:
现在它按我的要求工作