在Java中解析JSON并在UI中排列
我是JAVA新手,以前从未处理过JSON数据。 我必须创建一个新闻桌面应用程序,为此我发送了一个GET 请求一个web地址,我得到如下所示的JSON输出在Java中解析JSON并在UI中排列,java,json,Java,Json,我是JAVA新手,以前从未处理过JSON数据。 我必须创建一个新闻桌面应用程序,为此我发送了一个GET 请求一个web地址,我得到如下所示的JSON输出 ****OUTPUT in JSON**** { "status": "ok", "source": "the-hindu", "sortBy": "top", -"articles": [ -{ "author": "AP", "title": "Liu Xiaobo, Ch
****OUTPUT in JSON****
{
"status": "ok",
"source": "the-hindu",
"sortBy": "top",
-"articles": [
-{
"author": "AP",
"title": "Liu Xiaobo, Chinese dissident who won Nobel prize, dies",
"description": "He succumbed to cancer in a hospital while remaining under
police custody.",
"url": "http://www.thehindu.com/news/international/chinese-nobel-laureate-
liu-xiaobo-dies/article19271778.ece",
"urlToImage":"http://www.thehindu.com/news/international/Xiaobo",
"publishedAt": null
},
-{
"author": "Pavan Dahat",
"title": "BJP leader beaten for carrying ‘beef’",
"description": "A video of the incident that went viral on social media,
shows the attackers accusing the man of “ killing a cow.”",
"url": "http://www.thehindu.com/news/national/other-states/man-attacked-
in-
nagpur-for-allegedly-carrying-beef/article19269863.ece",
"urlToImage": "http://www.thehindu.com/news/national/other-
states/article19269862.ece/ALTERNATES/LANDSCAPE_615/beef1",
"publishedAt": null
},
]
}
现在,我必须解析这些JSON数据,并将标题与图像安排在适当的位置。我如何才能做到这一点?使用jackson2,您可以轻松做到这一点: 首先将jackson2添加为应用程序中的依赖项: 将其保存到数组列表中的示例:
//Declare an array list of the object that you want to use
private List<YourOwnObject> cart = new ArrayList<>();
//Create an instance of ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//Third pass your json string to the object mapper
this.cart = mapper.readValue(yourJsonResponseString, mapper.getTypeFactory().constructCollectionType(List.class, YourOwnObject.class));
//声明要使用的对象的数组列表
私有列表购物车=新的ArrayList();
//创建ObjectMapper的实例
ObjectMapper mapper=新的ObjectMapper();
//第三,将json字符串传递给对象映射器
this.cart=mapper.readValue(yourJsonResponseString,mapper.getTypeFactory().ConstructionCollectionType(List.class,YourOwnObject.class));
希望这有帮助!
关于,您可以使用Jackson库解析JSON。你可以看看。