【问题标题】:Jackson Json: Converting a Json Tree Node to an Java Object and add it to an ArrayListJackson Json:将 Json 树节点转换为 Java 对象并将其添加到 ArrayList
【发布时间】:2017-08-26 23:14:27
【问题描述】:

我仍然是 Java 和解析 Json 的新手。我正在尝试使用 Spring 构建一个 Comic Webapp。数据库是一个 Json 文件,其中包含一系列不同的漫画。 我想将 Json Array 转换为 Java Objects 并将其放入 ArrayList 但我似乎在此过程中的某个地方犯了错误。也许你可以告诉我我做错了什么?在进行 JUnit 测试时,我收到以下错误:

Error com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Comic" (class de.uni_koeln.comics.data.Comic), not marked as ignorable (6 known properties: , "title", "issue", "id", "box", "publisher", "comment"])
 at [Source: N/A; line: -1, column: -1] (through reference chain: de.uni_koeln.comics.data.Comic["Comic"])

漫画类

package de.uni_koeln.comics.data;

import de.uni_koeln.comics.service.JsonImportService;

public class Comic {
    private JsonImportService jservice;

public String title;
public int id;
public int issue;
public int box;
public String publisher;
public String comment;

public Comic() {

}
public Comic(String title, int issue, int box, String publisher, String   comment) {
        this.title = title;
        this.issue = issue;
        this.box = box;
        this.comment = comment;
        this.publisher = publisher;
    }

//setter and getter

` JsonImportService

package de.uni_koeln.comics.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;


@Service
public class JsonImportService {
    private List<Comic> comicList;

    @Test
    public void readComicJson() throws JsonParseException, JsonMappingException, IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(new File("src/main/resources/Comics.json"));
    Comic comic = mapper.treeToValue(root, Comic.class);

    JsonNode contactNode = root.path("Comic");
    if (contactNode.isArray()) {
        for (JsonNode node : contactNode) {

            String title = node.path("Title").asText();
            int issue = node.path("Issue #").asInt();
            int box = node.path("Box #").asInt();
            String publisher = node.path("Publisher").asText();
            String comment = node.path("Comments").asText();

            comic.setTitle(title);
            comic.setIssue(issue);
            comic.setBox(box);
            comic.setPublisher(publisher);
            comic.setComment(comment);
            comicList.add(new Comic(title,box,issue,publisher,comment));
        }
    }
}

public List<Comic> getComicList() {
    return comicList;
}

【问题讨论】:

  • 你能发布你的json文件吗?

标签: java json arraylist jackson


【解决方案1】:

尽量使用@JsonIgnoreProperties注解,比如blow。

@JsonIgnoreProperties(ignoreUnknown = true)

公开课漫画{

}

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多