简体   繁体   English

如何解析从 Google 的图像搜索 API 返回的这个 JSON 字符串?

[英]How to parse this JSON string returned from Google's image search API?

I have a JSON string:我有一个 JSON 字符串:

{"responseData": {
 "results": [
  {
   "GsearchResultClass": "GimageSearch",
   "width": "450",
   "height": "450",
   "imageId": "Yt3TRC1vxzhazM",
   "tbWidth": "127",
   "tbHeight": "127",
   "unescapedUrl": "http://www.touchnote.com/files/assets/STAN009.jpg",
   "url": "http://www.touchnote.com/files/assets/STAN009.jpg",
   "visibleUrl": "www.touchnote.com",
   "title": "Touchnote - Personalised \u003cb\u003eFuzzy Monkey\u003c/b\u003e greeting cards design by Dan \u003cb\u003e...\u003c/b\u003e",
   "titleNoFormatting": "Touchnote - Personalised Fuzzy Monkey greeting cards design by Dan ...",
   "originalContextUrl": "http://www.touchnote.com/photo/card-design/Fuzzy+Monkey",
   "content": "Card Design \u003cb\u003eFuzzy Monkey\u003c/b\u003e",
   "contentNoFormatting": "Card Design Fuzzy Monkey",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:Yt3TRC1vxzhazM:www.touchnote.com/files/assets/STAN009.jpg"
  },
  {
   "GsearchResultClass": "GimageSearch",
   "width": "640",
   "height": "480",
   "imageId": "c6093fGTdNvKOM",
   "tbWidth": "137",
   "tbHeight": "103",
   "unescapedUrl": "http://stuff.fuzzymonkeyphotography.com/front_page/NEW_NEW_logo3_480px.jpg",
   "url": "http://stuff.fuzzymonkeyphotography.com/front_page/NEW_NEW_logo3_480px.jpg",
   "visibleUrl": "www.fuzzymonkeyphotography.com",
   "title": "\u003cb\u003eFuzzy Monkey\u003c/b\u003e Photography",
   "titleNoFormatting": "Fuzzy Monkey Photography",
   "originalContextUrl": "http://www.fuzzymonkeyphotography.com/",
   "content": "Welcome to \u003cb\u003eFuzzy Monkey\u003c/b\u003e",
   "contentNoFormatting": "Welcome to Fuzzy Monkey",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:c6093fGTdNvKOM:stuff.fuzzymonkeyphotography.com/front_page/NEW_NEW_logo3_480px.jpg"
  },
  {
   "GsearchResultClass": "GimageSearch",
   "width": "500",
   "height": "375",
   "imageId": "oKdBN2qxw5JJoM",
   "tbWidth": "130",
   "tbHeight": "98",
   "unescapedUrl": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0",
   "url": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg%3Fv%3D0",
   "visibleUrl": "www.flickr.com",
   "title": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0",
   "titleNoFormatting": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0",
   "originalContextUrl": "http://www.flickr.com/photos/maryelizajade/1434841504/in/set-72157602146748073/",
   "content": "\u003cb\u003efuzzy monkey\u003c/b\u003e",
   "contentNoFormatting": "fuzzy monkey",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:oKdBN2qxw5JJoM:farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg%3Fv%3D0"
  },
  {
   "GsearchResultClass": "GimageSearch",
   "width": "500",
   "height": "375",
   "imageId": "GNgM5anX5NZYPM",
   "tbWidth": "130",
   "tbHeight": "98",
   "unescapedUrl": "http://farm1.static.flickr.com/38/91607831_009166aa41.jpg",
   "url": "http://farm1.static.flickr.com/38/91607831_009166aa41.jpg",
   "visibleUrl": "www.flickr.com",
   "title": "\u003cb\u003eFuzzy monkey\u003c/b\u003e sad face on Flickr - Photo Sharing!",
   "titleNoFormatting": "Fuzzy monkey sad face on Flickr - Photo Sharing!",
   "originalContextUrl": "http://www.flickr.com/photos/ajagendorf25/91607831/",
   "content": "\u003cb\u003eFuzzy monkey\u003c/b\u003e sad face",
   "contentNoFormatting": "Fuzzy monkey sad face",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:GNgM5anX5NZYPM:farm1.static.flickr.com/38/91607831_009166aa41.jpg"
  }
 ],
 "cursor": {
  "pages": [
   {
    "start": "0",
    "label": 1
   },
   {
    "start": "4",
    "label": 2
   },
   {
    "start": "8",
    "label": 3
   },
   {
    "start": "12",
    "label": 4
   },
   {
    "start": "16",
    "label": 5
   },
   {
    "start": "20",
    "label": 6
   },
   {
    "start": "24",
    "label": 7
   },
   {
    "start": "28",
    "label": 8
   }
  ],
  "estimatedResultCount": "578000",
  "currentPageIndex": 0,
  "moreResultsUrl": "http://www.google.com/images?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dfuzzy+monkey"
 }
}
, "responseDetails": null, "responseStatus": 200}

I'm getting this as a response from Google image search API .我收到了来自Google image search API的回复。 But when I try to parse it I always get failure with no result:但是当我尝试解析它时,我总是失败而没有结果:

JSONObject json = new JSONObject(builder.toString());

final JSONArray geodata = json.getJSONArray("results");
final int n = geodata.length();

for (int i = 0; i < n; ++i) {
    final JSONObject person = geodata.getJSONObject(i);
    System.out.println(person.geString("width"));
}

What am I doing wrong?我究竟做错了什么?

JSONObject json = new JSONObject(builder.toString());
//Add this line 
JSONObject responseData = json.getJSONObject("responseData");
final JSONArray geodata = responseData.getJSONArray("results");
final int n = geodata.length();

for (int i = 0; i < n; ++i) {
    final JSONObject person = geodata.getJSONObject(i);
    System.out.println(person.geString("width"));
}
 JSONParser parser=new JSONParser();
 Object obj = parser.parse(builder.toString());
 JSONArray array = (JSONArray)obj;
 System.out.println("The 2nd element of array");
 System.out.println(array.get(1));
 JSONObject obj2 = (JSONObject)array.get(1);

try this method.试试这个方法。

You can use Java API for JSON Processing ( JSR-353 ) to parse JSON.您可以使用 Java API for JSON Processing ( JSR-353 ) 来解析 JSON。 This standard provides a stream based (like StAX for XML) and object based (like DOM for XML, but lighter).该标准提供基于流(如 XML 的 StAX)和基于对象(如 XML 的 DOM,但更轻)。

For More Information想要查询更多的信息

Below are a couple of links to my blog that demostrate how to use these APIs:下面是我的博客的几个链接,它们演示了如何使用这些 API:

To convert your JSON string to hashmap use this :要将您的JSON 字符串转换为 hashmap,请使用以下命令:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

Use this class :) (handles even lists , nested lists and json)使用这个类:) (处理偶数列表、嵌套列表和 json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Google自定义Api搜索返回的Json中获取Java对象 - How to get Java Object from Json returned by Google Custom Api search 如何通过Google自定义搜索API创建JSON对象? - How to create a JSON object from Google Custom Search API? 如何解析地图对象<String, Object>从 Google Cloud Firestore 的 documentSnapshot.getData() 返回到 POJO? - How to parse Object of Map<String, Object> returned from documentSnapshot.getData() of Google Cloud Firestore into a POJO? 如何从Android应用程序连接到Flickr的Search Image API? - How to connect to Flickr's Search Image API from Android app? 将API返回的图像保存在JSON中 - Saving an image returned by an API in JSON 如何从 Json 字符串解析 Json 数组 - How to parse Json array from Json string 如何使用Java访问Google Api(userinfo)返回的JSON对象中的值 - How to access a value from JSON object returned by Google Api(userinfo) in Java 如何在android中解析此JSON(从.NET Web服务返回) - How to parse this JSON in android (returned from .NET webservice) 如何解析从php返回的数组到android中的字符串数组 - How to parse array returned from php to String array in android 如何使用Java解析Google Custom Search API响应? - How to parse Google Custom Search API response in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM