0

I am having some trouble trying to figure out how to parse a line in a json file so that it only returns part of the line as a string. I will illustrate below:

public String GetDistance(String origin, String destination) throws MalformedURLException, IOException {

    //URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins" + origin + ",UK+destination=" + destination + ",UK&key=mykey");
    URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Cornwall,UK&destinations=London,UK&key=mykey");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    String line, outputString = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {

        if (line.contains("distance")) {
            outputString = reader.readLine().trim();

            return outputString;
        }

    }

    return outputString;
}

What this function does is create a json file in my browser using Google Maps API:

{
   "destination_addresses" : [ "London, UK" ],
   "origin_addresses" : [ "Cornwall, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "284 mi",
                  "value" : 456443
               },
               "duration" : {
                  "text" : "4 hours 52 mins",
                  "value" : 17530
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Currently the "outputString" returns the line: "text" : "284 mi". However, the desired output is to just return the miles, "284".

I know this is most likely a re post, however I have been searching around for a solution to this and have been unsuccessful in implementing something that works.

Any help on this would be greatly appreciated, Cheers.

Seano989
  • 15
  • 1
  • 5
  • see https://cstheory.stackexchange.com/questions/3987/is-json-a-regular-language – Alice Oualouest Dec 03 '18 at 14:44
  • @Alice Oualouest Sorry, I don't understand how I can use this post to answer my question – Seano989 Dec 03 '18 at 14:47
  • You could just split the string using the ":" character as the split separator and get the second element like following String[] s = reader.readLine().trim().split(":"); String val = s[1].substring(1,s[1].length()); – NickAth Dec 03 '18 at 14:49
  • 1
    As an adendum the answer given, if you wanted a more accurate value, the rows.elements.distance.value element (456443) is the distance in meters, rather than miles. This can then be converted to miles with your preferred precision. – Chris Dec 03 '18 at 14:54
  • You could instead read the `value` rather than text and divide it by `1609.344` to convert from meters. When designing a system that uses these unit types, it's best to plan ahead for conversion, or in case someone wants the results in SI units, rather than imperial. – coladict Dec 03 '18 at 14:56

1 Answers1

0

You can have 2 solutions:

  1. Parse the JSON and treat it as an object and then just return the String you're looking for.

  2. Split the line as follows:

    outputString = reader.readLine().trim();
    

    That line above returns "text" : "284 mi"

    Then you need to split the line by ::

    outputString.split(":")
    

    That should create an array with 2 Strings: "text" and "284 mi"

    Then take the second String and split it by a space and take the first String:

    outputString.split("\\s")
    

    Now you have: "284

    Then just return it from subindex 1 till the end, see docs:

    outputString.substring(1)
    

    And then just put it all together:

    return outputString.split(":")[1].split("\\s")[0].substring(1)
    

I haven't tried above code but it should work.

BTW follow Java Naming Conventions

  • firstWordLowerCaseVariable
  • firstWordLowerCaseMethod()
  • FirstWordUpperCaseClass
  • ALL_WORDS_UPPER_CASE_CONSTANT

And use them consistently

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • Hey thanks for the reply, I have tried to implement this but I am getting an error that says: "java.lang.StringIndexOutOfBoundsException: String index out of range -1" – Seano989 Dec 03 '18 at 15:50
  • Please ignore my previous message, I took the logic of what you proposed and managed to implement a solution that works perfectly, thank you for the help! – Seano989 Dec 03 '18 at 15:54
  • I'm glad I was of help, anyway I'll give it a try later. I wrote the answer on the phone @Seano989 – Frakcool Dec 03 '18 at 15:59