在Java NetBeans中解析JSON字符串



谁能告诉我如何从每个元标签中获得og:description, og:title, book:release_date, book:authorbook:isbn的值?(请参阅下面的JSON内容)最终这些值将显示在一个表中,所以我需要它们作为Java对象(字符串)..

到目前为止,我已经尝试使用许多外部库,但这是我使用JSON的第一个项目,所以我不明白他们是如何工作的。

对于您的信息,我正在使用NetBeans,并正在制作restful web服务。

我已经设法将这些转换成JSON字符串使用这个代码:

    JSONObject obj = new JSONObject(builder.toString());
    String theJsonString = obj.toString();

但是当我尝试这样做时:

    ObjectMapper mapper = new ObjectMapper();
                  Map<String,Object> data = mapper.readValue(theJsonString.getBytes(), Map.class);
                  Map items = (Map) data.get("items");
                  Map pagemap = (Map) items.get("pagemap");
                  Map metatags = (Map) pagemap.get("metatags");
                  String b_title = (String) metatags.get("og:title");
     System.out.println(b_title);

我得到这个错误:

. lang。ClassCastException: java.util.ArrayList不能强制转换为java.util.MapAPI.GCustSearchAPI.main (GCustSearchAPI.java: 77)

第77行是这样的

Map items = (Map) data.get("items");

下面是json的内容:

{
"items": [
{
"pagemap": {
"metatags": [
 {
  "og:description": "A boxed set, including the titles 'Harry Potter and the Philosopher's Stone', 'Harry Potter and the Chamber of Secrets', 'Harry Potter and the Prisoner of Azkaban', 'Harry Potter and the Goblet of Fire', 'Harry Potter and the Order of the Phoenix', 'Harry Potter and the Half-Blood Prince' and 'Harry Potter and the Deathly Hallows'.",
  "og:title": "Harry Potter Adult Paperback Boxed Set: Adult Edition (Paperback)",
  "book:release_date": "2008-10-06",
  "book:author": "J. K. Rowling",
  "book:isbn": "9780747595847"
 }
]
}
},
 {
"pagemap": {
"metatags": [
 {
  "og:description": "Offers an in-depth look at the craftsmanship, artistry, technology, and more than ten-year journey that took the world's bestselling fiction from page to screen. From elaborate sets and luxurious costumes to advanced special effects and film making techniques, this title chronicles all eight films.",
  "og:title": "Harry Potter: Page to Screen (Hardback)",
  "book:release_date": "2011-10-25",
  "book:author": "Bob McCabe",
  "book:isbn": "9780857687753"
 }
 ]
}
 }
 ]
}

如有任何意见,将不胜感激。请告诉我在一个简单的方式,因为我是一个初学者(刚刚接触NetBeans 2个月)。多谢! !

如果您查看json items是一个数组,则相应的java表示是一个列表。所以你需要获取items作为List

List items = (List ) data.get("items");

同样的逻辑也适用于metatags

List metatags = (List) pagemap.get("metatags");

用上面提到的修改,试试这个

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> data = mapper.readValue(file, Map.class);
List<Map<String, Object>> items = (List) data.get("items");
for (Map<String, Object> item : items) {
    Map pagemap = (Map) item.get("pagemap");
    List<Map<String, Object>> metatags = (List) pagemap.get("metatags");
    for (Map<String, Object> tag : metatags) {
        String b_title = (String) tag.get("og:title");
        System.out.println(b_title);
    }
}

创建一个Java类item.java,并写入

Item item= mapper.readValue(new File(theJsonString.getBytes()), Item .class);

然后读取json

相关内容

  • 没有找到相关文章

最新更新