我正在使用gson
库从http请求中获取json。
一切正常,除了我比较从请求收到的字符串的部分。即使字符串完全相同,由于某种原因string.equals
方法失败。作为输出,它始终打印different dates
。
这种行为的原因是什么?我在这里缺少什么?
BufferedReader br;
try{
String url = "http://date.jsontest.com/";
URL request_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)request_url.openConnection();
conn.setRequestMethod("GET");
if (200 == conn.getResponseCode()){
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String jsonLine = "";
String line ;
while ((line = br.readLine()) != null) {
jsonLine += line;
}
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
try{
String result = jobject.get("date").toString();
System.out.println("res: " + result);
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
}
catch (NullPointerException ex){ }
}
}
catch (JsonSyntaxException ex){}
catch (IOException ex) {}
答案 0 :(得分:3)
String result = jobject.get("date").toString();
以上行返回date
的字符串表示形式,即带有引号:"05-29-2017"
以及equals
方法返回false
的原因{{1由于开头和结尾的双引号,它将是"\"05-29-2017\"".equals("05-29-2017")
如果您想要实际值,则需要使用false
方法,例如以下应该有效:
getAsString