尝试使用内部对象从json映射到域模型

时间:2014-03-10 11:04:29

标签: java json jackson

我有一个Json:

    "{\"userID\":2,\"title\":\"jfsdk\",\"content\":\"dskljf\",\"tagList\":{\"name\":\"fysikk\",\"name\":\"Matte\",\"name\":\"Kjemi\"}}"

我想解析一个Domain Model类

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;}

里面还有一个Tag类:

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");
    }
}

当我有“得到(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 个答案:

答案 0 :(得分:0)

我重新设计了我的前端代码,所以JSON我看起来像是MichałZiober提到的那样:

    {"userID":2,"title":"foo","content":"bar","tagList":["Fysikk","Matte"]}

现在它可以按照我的意愿行事!