过去几个小时我一直在努力解决这个问题。当涉及到 Java 时,我有点生疏,并决定我想完成这个方法,我试图解析 json 以获取 map 的名称。
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"] 而不是字符串。
最佳答案
检查 JSON 来源。看起来它可能没有 "周围的名称值,或者名称是一个对象。 例如:
...
"name":John Doe,
...
or
"name":{"first":"John", "last":"Doe"},
...
顺便说一句:第二个更值得期待。 First之前肯定是失败了,因为是错误的JSON。周围没有 "的值必须是数字。但也许名称是空的,例如:
...
"name":,
...
关于java - JSONObject ["name"] 不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516842/