JSONObject [“name”]不是字符串

时间:2016-11-09 22:09:02

标签: java json

过去几个小时我一直在努力解决这个问题。谈到Java时我有点生疏,并决定我想完成这个方法,我试图解析json以得到地图的名称。

private static void mapLookUp (String mapId){
    HttpClient httpclient = HttpClients.createDefault();


    try
    {
        URIBuilder builder = new URIBuilder("https://www.haloapi.com/metadata/h5/metadata/maps");

        URI uri = builder.build();
        HttpGetWithEntity request = new HttpGetWithEntity(uri);
        request.addHeader("ocp-apim-subscription-key", "aa09014c153b4a4b9c3a4937356e208a");

        // Request body
        StringEntity reqEntity = new StringEntity("{body}");
        request.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) 
        {
            String response2request = EntityUtils.toString(entity);
            //System.out.println(response2request.length()+"\n"+response2request);

            String jsonString = "{\"Results\":"+response2request+"}";
            System.out.println(jsonString);

            JSONObject jsonResult = new JSONObject(jsonString);
            List<String> mapName = new ArrayList<String>();
            List<String> mapIds = new ArrayList<String>();
            JSONArray array = jsonResult.getJSONArray("Results");
            for(int i = 0 ; i < array.length() ; i++){
                mapName.add(array.getJSONObject(i).getString("name"));
                mapIds.add(array.getJSONObject(i).getString("id"));}
            for(int i = 0 ; i < mapIds.size() ; i++)
                if(mapIds.get(i).equals(mapId))
                    System.out.println("The most recent game was on "+mapName.get(i));
        }
        else
            System.out.println("NULL");
    }
    catch (Exception e)
    {

        System.out.println("Caught exception");
        System.out.println(e.getMessage());
    }
}

在输出中,我得到JSONObject [“name”]而不是字符串。

1 个答案:

答案 0 :(得分:1)

检查JSON源。似乎它可能没有“名称值,或名称是一个对象。 例如:

...
"name":John Doe,
...
or
"name":{"first":"John", "last":"Doe"},
...
顺便说一下:第二个更期待。首先必须失败,因为它是错误的JSON。没有“周围的值必须是一个数字。但是名字可能是空的,如:

...
"name":,
...