从json对象获取字符串不起作用

时间:2017-05-29 16:03:41

标签: java json gson

我正在使用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) {}

1 个答案:

答案 0 :(得分:3)

String result = jobject.get("date").toString();

以上行返回date的字符串表示形式,即带有引号:"05-29-2017"以及equals方法返回false的原因{{1由于开头和结尾的双引号,它将是"\"05-29-2017\"".equals("05-29-2017")

如果您想要实际值,则需要使用false方法,例如以下应该有效:

getAsString