Getting string from json object doesn't work

I am using a library gson

to get json from an HTTP request. Everything works fine except for the part where I compare the string I got from the request. Even if the string is exactly the same, the method string.equals

fails for some reason . And as output, it always prints different dates

.

What is the reason for this behavior? What am I missing here?

 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) {}

      

+3


source to share


1 answer


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

      

The above string returns a string representation date

i.e. with quotes around it: "05-29-2017"

and so the method equals

returns false

( "\"05-29-2017\"".equals("05-29-2017")

would be false

because of the double quotes at the beginning and end)



If you want the actual value you need to use a method getAsString

like. the following should work:

String result = jobject.get("date").getAsString();
if(result.equals("05-29-2017"))
    System.out.println("Same date");
else
    System.out.println("different date");

      

+3


source







All Articles