我需要从JSON获取一个值,但是我将null作为值。
public class PlaceTest {
public void sendRequest() throws Exception{
URIBuilder builder = new URIBuilder("https://maps.googleapis.com/maps/api/place/findplacefromtext/json");
builder.addParameter("key","mykey");
builder.addParameter("input","London");
builder.addParameter("inputtype","textquery");
HttpGet getReq = new HttpGet(builder.build());
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(getReq);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder builders = new StringBuilder();
String s;
while ((s = reader.readLine())!=null){
builders.append(s+"\n");
}
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(builders.toString());
JsonNode candidates = node.get("candidates");
System.out.println(candidates.get("place_id"));
//json
System.out.println(builders.toString());
}
}
JSON代码为:
{"candidates":[{"place_id" : "ChIJdd4hrwug2EcRmSrV3Vo6llI"}],"status" : "OK"}
答案 0 :(得分:3)
在上述JSON candidates
中,值是JsonArray
JsonNode node = mapper.readTree(builders.toString());
JsonNode candidates = node.get("candidates");
现在迭代JsonArray
并获得place_id
:
if (candidates.isArray()) {
for (JsonNode objNode : arrNode) {
System.out.println(objNode.get("place_id"));
}
}