0

I am trying to communicate from Java->JS in Android through the use of JSON. I currently create the JSON like so in Java:

JSONObject latLng = new JSONObject();
latLng.put("lat",20.000);
latLng.put("lon",20.000);

JSONArray jsonArray = new JSONArray();
jsonArray.put(latLng);


JSONObject destination = new JSONObject();
destination.put("destination", jsonArray);

passToJs(destination); //theoretical - method looks slightly different

Then, if I log what has been received in JS(lets call it 'data'), the result is the following:

{  
   "destination":[  
      {  
         "lat":20.000,
         "lon":20.000
      }
   ]
}

I am having some problem accessing the individual lat/lon values. I've tried:

data[0]
data[0].lat
data.lat

How do I read and save lat/lon to new variables? BTW, I think my JSON is not so good - is it better to just create a single JSON Object and pass that alone?

Thanks.

2
  • try data['destination'][0].lat Commented Apr 17, 2018 at 19:24
  • 1
    problem was with parsing - see comments on @Comforse answer below Commented Apr 17, 2018 at 19:41

1 Answer 1

2

You are missing the destination node in your object. You should use data.destination[0].lat

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, I've tried that too in the past, but anyway here it is again with the error: (first line is simply data being logged as a whole) {"destination":[{"lat":20.000,"lon":20.000}]} navigation.js:5 Uncaught TypeError: Cannot read property '0' of undefined
Try doing JSON.parse(data) and see if that helps. It may be that the data is seen as plaintext.
Awesome! That seemed to be the problem!! Thanks alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.