How to create a JSONArray that contains Javascript code inside Java? - 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.

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

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.

Also you could use Regular expressions to remove the ", if you parse the json to another language

i had a similar problem, the way i made this work:
instead of writing the javascript before the json conversion, insert a placeholder.
locations.put("%mapsPlaceholder1%");
then after filling the array with placeholders, do:
locations.toString().replaceFirst("\"%mapsPlaceholder1%\"","yourJsCode");
something like that
you could also just create the array string manually

Related

Get JSON data from JAVA component to XWiki apache velocity

What is the best way to get JSON data from a java component in xwiki runnung apache. In my java
component I'm compiling JSONObjects and JSONArrays, I would like to return
this data to my velocity script in JSON format, is this possible?
something like:
{{velocity wiki="false"}}
#if("$!request.outputSyntax" != '')
$response.setContentType('application/json')
#end
#set($map = {})
#set ($rightIN = ${request.rightIN})
#set ($spacenameIN = ${request.spacenameIN})
#set($disgard =$map.add($services.getjsondata.javacomp($spacenameIN,$rightIN)))
$jsontool.serialize($map)
{{/velocity}}
and the Java:
public JSONObject javacomp(String spacenameIN, String rightIN ){
JSONObject obj = new JSONObject();
try {
obj.put("spacenameIN ", spacenameIN );
obj.put("rightIN", rightIN );
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
At the end I would like to access this json object as a data return from an
ajax call. Is this possible?
I'm currently returning strings, but this is very inefficient how can I return objects?
In your code above, the Java component returns a JSONObject but then, in Velocity, you try to add that object directly to a map, not specifying any key.
So your velocity code should be changed to:
#set ($map = $services.getjsondata.javacomp($spacenameIN, $rightIN))
...since the JSONObject instance is pretty much a map.
After that, it's perfectly fine to serialize that map to JSON with:
$jsontool.serialize($map)
At the end I would like to access this json object as a data return
from an ajax call. Is this possible?
Sure, just remember to also set the content type of your result in Velocity, so that your ajax call properly interprets the Velocity result as JSON, and not as regular text. To do that you need to do:
#set ($discard = $response.setContentType('application/json'))
I'm currently returning strings, but this is very inefficient how can
I return objects?
Your Java component (script service) always returns objects to the Velocity side (they both execute on the server). It' your choice if those objects are strings or any other data type. You do not really need to handle the JSON serialization in the Java component (you just need to be careful that they are serializable types that $jsontool can handle when it will be called on the Velocity side). On the Velocity side, you do something with those objects and serialize them to JOSN (which is text/strings in the end because that's what the AJAX call needs since JavaScript is executed on the client side).
Additionally, I would suggest you avoid JSONObject altogether and use a regular Map to pass your results to the Velocity side.

Read a Java array in Javascript

I've a method that returns a 2d-array in java : public Object[][] getArray1() {}
I used println() to print it's content and i see that its well created.
On Javascript i assign this array to a var:
var content ="#{BDEStats.getArray1()}";
But i dont seem able to acess it's data. it always returns java.Lang.object; #... How can i do to display the content this array holds?
I've tried to cycle the array but i dont know how to refer to the objects it is holding. if i use content[1] to returns a char in that índex..! Kinda lost here
I think you may convert the array to JSON format before assigning it to javascript.
You can use some JSON framework to do this convert like:
JSON-lib
Jackson
Here a tiny Jackson demo:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
...
public static void main(String[] args) throws JsonProcessingException {
String[][] data = new String[1][2];
data[0][0] = "abc";
data[0][1] = "def";
System.out.println(new ObjectMapper().writeValueAsString(data));
}
This is the normal array String representation in Java, consisting in:
A number of [ based on the dimension
Either a letter for the primitive type (i.e. I for int), or L[fully qualified class name] for Objects
#
The array's hash code
For one-dimensional arrays, use java.util.Arrays.toString(myArray).
For multi-dimensional arrays, use java.util.Arrays.deepToString(myArray).
Edit (adding previous comment to answer)
You probably want to investigate JSON.parse to parse your Java array from JavaScript.
To turn a Java array into a string representation in a syntax which can be interpreted by a JavaScript engine, you need to turn it into the JavaScript Object Notation, or JSON for short.
There are many libraries available for Java to do this. Software recommendations are off-topic on Stackoverflow, but this article which compares 5 different libraries helped me to pick one for my project.
On the JavaScript side, you just have to use var content = JSON.parse(stringFromJava).
Or when you generate the JS code procedurally on the Java side, you can just embed the JSON string right into the sourcecode. This works because JSON is valid Javascript code for an object literal. In Java, this would look something like this:
scriptCode.append("var content = " + arrayAsJsonString + ";\n");
Ok problem solved. This was how I did it:
Instead of returning a Java Array I returned a JSON object in my method.
This JSON Object has a name and several other fields per ex:
(I'm getting my data from a Java List, so I iterate the list to populate the JSON object)
SONObject jsonObj = new JSONObject();
jsonObj.clear();
for (int tt=0; tamanho>tt ; tt++) {
try {
jsonObj.put("aa"+tt, ListaJobStats.get(tt).getName());
jsonObj.put("bb"+tt , new BigDecimal(ListaJobStats.get(tt).getAge() ....
After this if I printOut the JSON object in java i get a string:
aa0: '1st name'; aa1: ' 2nd name' ; bb0: 'age'; bb1: '2nd age' ... etc etc
After this in Javascript i get my JSON Object thorugh JSF like this:
var content=#{JAVACLASS.METHODTHATRETURNSJSON};
I stringify this object in JS:
var pars= JSON.stringify(content);
and i create the JSON object
var json = JSON.parse(pars)
Now I Iterate this JSON object in JS like this:
for (var tt=0; tamanho>tt ; tt++) {
[now im specifically adding the values to create a graphic but its just na exemple how u can acess te object]
data.setValue(tt, 0, json["aa"+tt]);
data.setValue(tt, 1, json["bb"+tt]);
...
Hope it will be useful. Take care

Java parsing JSON in args

Can you anyone help me with problem of parsing args in java?
I need to read JSON data by args in two formats(file, text arg). If an arg is path to file with JSON text, it's working.
In main method I'm reading args:
public static void main(String[] args){
String argText = args[1]
}
But if I'm put to arg some JSON text (for example: {"server1":{"dname":"www.server.com","lat":"40","lng":"17"}) it's problem with quotes, because in
String argText is stored text without quotes:
System.out.println("Text: " + argText);
Text: {server1:{dname:www.server.com,lat:40,lng:17}
And method for parsing JSON:
public static JSONObject parseJSON(String argText){
if (text.contains("{")){
//arg is text and I want to store it as JSONObject
// how to store text with "
} else {
//argText is file....
// read file, put in new JSONObject
// it works without any problems.
}
return JsonObject
}
I don't know it is the good way to read input args, but for file it's working and I would to add reading form the text.
If argText contains escaped quotes \\\" everythig is OK, but I don't have text in these format.
EDIT:
So I don't have problem with parsing JSON bud I need some method that doing:
public static void(String quotedText){
//do something...
System.out.print("Output: " + text);
}
with in/out:
< '"text":"val1","val2","val3"'
Output: "text":"val1","val2","val3"
In Win system.out.print is:
'Output: text:val1,val2,val3'
The quotes are munged by the shell; put the whole string in single quotes for that to work. If your utility is launched by some other program, fix that program to escape everything, or transport it using stdin.
If using library does not suit your needs, you can make a simple method to covert it.
Add " after every {, before every }, and both before and after every , and :.
There might be some ambiguity with those chars, but that why quotes are supposed to be there at first place.
Maybe you should use some standard library for parsing JSON, it will really save you a lot of time. JSON isn't that simple that you can just treat it like a simple string.
Try:
http://jackson.codehaus.org/
https://code.google.com/p/json-simple/
You should try a standard library to parse JSON, like Alexander said.
There are some out there that convert JSON into Java objects. I personally like XStream. Try this JSON with Xtream tutorial
With it, you can define your own Java objects and use the library to convert JSON to those objects and from the objects to JSON. No need to create your own parser.
I recommend this simple and widely used library: GSON

JSon to CSV with Java using CDL: possible to replace comma-sep. by semi-colum sep. values?

Everything is in the title :)
I'm using org.json.CDL to convert JSONArray into CSV data but it renders a string with ',' as separator.
I'd like to know if it's possible to replace with ';' ?
Here is a simple example of what i'm doing:
public String exportAsCsv() throws Exception {
return CDL.toString(
new JSONArray(
mapper.writeValueAsString(extractAccounts()))
);
}
Thanks in advance for any advice on that question.
Edit: No replacement solution of course, as this could have impact for large data, and of course the library used enable me to specify the field separator.
Edit2: Finally the solution to extract data as JSONArray (and String...) was not very good, especially for large data file.
So i made the following changes:
use a Java CSV library (for example: http://www.csvreader.com/java_csv_samples.php)
refactor code to stream data from json input source to csv output source
This is nicer for large data treatment. If you have comments do not hesitate.
String output = "Hello,This,is,separated,by,a,comma";
// Simple call the replaceAll method.
output = output.replace(',',';');
I found this in the String documentation.
Example
String value = "Hello,tthis,is,a,string";
value = value.replace(',', ';');
System.out.println(value);
// Outputs: Hello;tthis;is;a;string

Java : How to assign Json formated String to Java String?

I have a big json string which i will be getting as a request from the UI , which will be converted to a String and parsed .
I want to simulate the similar environment for testing locally , so for this purpose i captured the JSon format.
Currently i am manually adding "/" to this big json string .
Is there any other way to achieve this ??
For example i got this json
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"Preethi"}
and converted that into
String str = "{\"age\":\"29\",\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"mkyong\"}";
Is there any other way to achieve this ??
On the client-side, do a search and regex "replace all" of double-quotes into single quotes on the desired form field before actually sending the request.
Actually, Java doesn't have verbatim string literals.
If you want a Java-like (and Java-VM-based) language that does, however, you might want to look at Groovy which has various forms of string literal.
we have in build method to convert jsonObject to string. Why don't you use that.
JSONObject json = new JSONObject();
json.toString();

Categories