我的json表示与这里完全相同:https://newsapi.org/docs/endpoints/top-headlines
为了将其反序列化为java对象,我创建了一个 News
和一个 Article
班级。 News
包含多个 Articles
. 以下是我的课程:
新闻:
public class News {
private String status;
private int totalResults;
private Article[] articles;
public News() {
}
public News(String status, int totalResults, Article[] articles) {
this.status = status;
this.totalResults = totalResults;
this.articles = articles;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getTotalResults() {
return totalResults;
}
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
public Article[] getArticles() {
return articles;
}
public void setArticles(Article[] articles) {
this.articles = articles;
}
}
文章:
public class Article {
private String source;
private String author;
private String title;
private String description;
private String url;
private String imageUrl;
private String publishedAt;
private String content;
public Article() {
}
public Article(String source, String author, String title, String description, String url, String imageUrl,
String publishedAt, String content) {
this.source = source;
this.author = author;
this.title = title;
this.description = description;
this.url = url;
this.imageUrl = imageUrl;
this.publishedAt = publishedAt;
this.content = content;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
现在我用的是 com.fasterxml.jackson.databind.ObjectMapper
将json表示反序列化为 News
对象:
ObjectMapper objectMapper = new ObjectMapper();
News news = objectMapper.readValue(response.toString(), News.class);
在这里我得到一个 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of
java.lang.Stringout of START_OBJECT token
问题显然是用json表示的文章数组。我读过jackson中关于数组反序列化的内容,但没有发现任何关于包含属性和对象数组的对象反序列化的内容。https://www.baeldung.com/jackson-deserialization
如何使用 ObjectMapper
? 我错过什么了吗?感谢您的帮助,谢谢!
1条答案
按热度按时间bbmckpt71#
你的源代码Map错误
source
字段的格式为这可以替换为
更换
具有
在
Article
班