错误 com.fasterxml.jackson.core.JsonParseException:无法识别的令牌

Error com.fasterxml.jackson.core.JsonParseException: Unrecognized token

试图读取一个JSON文件并将其序列化为java对象,我写了一个方法:

public static PostPojo readFile(String titleFile){
    String pathJSONFile = "src/main/resources/"+titleFile+".json";
    ObjectMapper objectMapper = new ObjectMapper();

    try {
         objectMapper.readValue(pathJSONFile,PostPojo.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return postPojo;
}

但它产生错误:

    com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'src': was expecting (JSON 
    String, Number, Array, Object or token 'null', 'true' or 'false')
    at [Source: (String)"src/main/resources/ninetyNinthPost.json"; line: 1, column: 4]
    at utils.ApiUtils.readFile(ApiUtils.java:71)
    at ApiApplicationRequest.getValue(ApiApplicationRequest.java:31)

我的 JSON 计算值的文件

[ {
 "userId" : 10,
 "id" : 99,
 "title" : "temporibus sit alias delectus eligendi possimus magni",
 "body" : "quo deleniti praesentium dicta non quod\naut est 
 molestias\nmolestias et officia quis nihil\nitaque dolorem quia"
} ]

我的java对象class

public class PostPojo {

private int userId;
private int id;
private String title;
private String body;
public PostPojo() {
}

public PostPojo(int userId, int id, String title, String body) {
    this.userId = userId;
    this.id = id;
    this.title = title;
    this.body = body;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}


@Override
public String toString() {
    return "PostModel{" +
            "userId=" + userId +
            ", id=" + id +
            ", title='" + title + '\'' +
            ", body='" + body + '\'' +
            '}';
}
}

我真的不明白什么是reason.As我明白了,在文档中阅读,它应该读取文件并将其呈现在java class中。有什么建议吗?

没有方法签名应该获取文件路径作为第一个参数。您可以传递一个 JSON 字符串作为第一个参数,或者您可以使用带有文件对象的方法签名作为第一个参数,如下所示:

public static PostPojo[] readFile(String titleFile){
    String pathJSONFile = "src/main/resources/"+titleFile+".json";
    ObjectMapper objectMapper = new ObjectMapper();
    File jsonFile = new File(pathJSONFile);

    PostPojo[] postPojo = null;
    try {
        postPojo = objectMapper.readValue(jsonFile, PostPojo[].class);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return postPojo;
}

编辑:由于您的文件在对象周围定义了一个包装数组,因此您必须将其解析为数组。之后你可以 return 它作为一个数组,就像我在我编辑的答案中所做的那样,或者你只是 return 第一个数组记录。