[英]Getting string from json object not working
我正在使用gson
库从http请求中获取json。 一切正常,除了我比较从请求收到的字符串的部分。 即使字符串完全相同,由于某种原因, string.equals
方法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) {}
String result = jobject.get("date").toString();
上面的行返回date
字符串表示,即带有引号: "05-29-2017"
,这就是为什么equals
方法返回false
( "\\"05-29-2017\\"".equals("05-29-2017")
由于开头和结尾的双引号, "\\"05-29-2017\\"".equals("05-29-2017")
将是false
)
如果你想要实际值,你需要使用getAsString
方法,例如以下应该工作:
String result = jobject.get("date").getAsString();
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.