Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JSONArray that contains Javascript code inside Java?

I am creating a JSONArray and parse it to a String, but as it even contains Strings instead of code it doesn't output as I need it.

for(Place place: places){
    locations.put("new google.maps.LatLng("+place.getContactData().getLatitude()+","+place.getContactData().getLongitude()+")");
}
return locations.toString();

It outputs as: ["new google.maps.LatLng(53.5608,9.96357)","new google.maps.LatLng(53.5608,9.96357)"] but I need it without quotation marks like [new google.maps.LatLng(53.5608,9.96357),new google.maps.LatLng(53.5608,9.96357)] to be correctly interpreted by javascript.

like image 340
Lester Avatar asked Aug 15 '26 15:08

Lester


2 Answers

Another method would be:

create an array with just the coordinates:

for(Place place: places){
    JSONObject obj = new JSONObject();
    obj.put("lat",place.getContactData().getLatitude());
    obj.put("lng",place.getContactData().getLongitude());
    locations.put(obj);
}

and then in javascript:

var places = (yourPlacesJson);
var placeObjects = [];

for(var i=0;i<places.length;i++)
{
    placeObjects[placeObjects.length] = new google.maps.LatLng(places[i].lat,places[i].lng);
}
like image 178
x4rf41 Avatar answered Aug 18 '26 06:08

x4rf41


JSON only supports plain-old-data. It can't include any executable code (a new is executable code). This is by design - when JSON would be able to include executable code you would have to be much more carefully with importing JSON from an untrusted source.

All you can do is pass javascript code as strings and eval() it on the JS side after parsing the JSON.

like image 41
Philipp Avatar answered Aug 18 '26 06:08

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!