Get JSON data from JAVA component to XWiki apache velocity - java

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.

Related

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

How to parse json java object in javascript

Here is my code :
Display.jsp:
<%
response.setContentType("application/json");
JSONObject json = new JSONObject();
Employee employee = new Employee("RAM","ram#gmail.com");
json.put("employee",employee);
out.println(json);
%>
how can i parse employee name and email using js,
i want to set those values into a table
Any ideas...
You can traverse thorough the object in the javascript to print its key and value ,
function inside_obj(o) {
var Otype = typeof o
if (Otype == "object") {
for (var key in o) {
print("key: ", key)
inside_obj(o[key])
}
} else {
print(o)
}
}
Learn More. .
Js runs on the client-side, whereas JSP - on the server side. Therefore, if you want to parse your JSP output HTML on the client side, you'll need to select this output (using jQuery is the most convenient way. Make sure you output it in a HTML tag with an ID you can use in jQuery selector). Then, use JSON.parse() to parse the json.
Also, why do you need JS to process your JSON? Can't you do that on the server side? Unless you're using AJAX, I can hardly think of a reason not to completely process your model on the server side.

Access fields of returned Java Object

I made a simple client call to the XML-RPC WordPress API/Posts using a xml-rpc client and according to their documentation here it returns a struct. How can i access the return values.
Here is a look at my code:
XmlRpcClient client = new XmlRpcClient("http://www.mywebsite.net/xmlrpc.php", false);
String[] fields = new String[4];
fields[0] = "post_id";
fields[1] = "post_title";
fields[2] = "post_date";
fields[3] = "post_content";
Object token = client.invoke("wp.getPost", new Object[]{"0","myusername", "mypassword", 1545, fields });
System.out.println(token);
When I print use
System.out.println(token);
I get the following out put:
{item_one=I am item number one, item_two=I am Item two...}
How can I access item_one and item_two?
There's a bit of information missing (what's the fully qualified name of XmlRpcClient?), but assuming that client.invoke actually returns just an Object and not something more specific that has accessor methods, you can parse the response using something like this:
Object token = client.invoke("wp.getPost", new Object[]{"0","myusername", "mypassword", 1545, fields });
String[] items = token.toString().split(",");
for (String item : items) {
String[] parts = item.split("=");
String key = parts[0];
String value = parts[1];
// do stuff with your keys and values here
}
Of course this isn't perfect code -- you may need to check for nulls, use String.trim(), etc, but it should get you started.
You don't have a true Java representation of the data returned, in that you don't have an object on which you can access
token.item_one
rather you have a string containing a representation of a set - that is something that (in concept) from which you could retrieve an value by its name
token.get("item_one")
This string format is probably JSON, which pretty much looks like JavaScript, and hence can represent quite complex data. In general you can have arrays of objects and objects containing objects (for example, a Customer might contain an Address object)
So you have two possibilities:
1). parse the string into a true Java representation such as one of the standard Java collection classes. You then use the get-by-name style I show above.
2). define a Java class that mimics the structure of the data and then parse the string to fill out such an object, you can then use the "dot" form of access - you really have a Java Object representing the data.
In the first case there are suitable libraries such as quickJson
For the second you can use implementations of standards such as JAX/B, which tends to be more work as you may need to construct the target Java Class by hand. Enterprise Java runtimes will give you these facilities and perhaps tooling to help, or look at implementaitons such as Jackson. You will see that JAX/B hada focus on mapping from XML to Java, but tutorials such as this show how to work with JSON instead.
My guess is that the first option, simple parsing to a collection may be enough for you.

Returning multiple sets of data using JSON with Java and JQuery

I want to send sets of data from servlet to the jsp using JSON. To elaborate, what exactly I want to do is take multiple rows from the database and print their values in jsp. I done with the part of DB connectivity and fetching of data. But I could not find a way to forward them to jsp using JSONObject. Each row has multiple attributes(column values). Please help me solve the problem.
What I'm doing is:
Collection <JsonObject> c=new ArrayList();
JsonObject j[] = null;
for(int i=0;i<uid_list.size();i++){//uid_list contains all the user_id's from the database
j[i].add("uid", j[i]);
j[i].add("fname", j[i]);
j[i].add("lname", j[i]);
j[i].addProperty("uid", uid_list.get(i).toString());
j[i].addProperty("fname", fname_list.get(i).toString());
j[i].addProperty("lname", lname_list.get(i).toString());
c.add(j[i]);
}
Also, is there any difference between JsonObject and JSONObject? The latter could not be recognized in servlet and by using JsonObject the put method is not recognized.
Aside from your code trying to insert into an uninitialized array, there are many JSON library for Java. You need to provide more details which one you're using
Also if your objective is just passing the JSON string into the browser, you might not even need jsp, you can just write the string version of the JSON object directly into the HttpResponse
Firstly, the JspnObject array has to be instantiated before it is used. Therefore, this means the following:
JsonObject j[] = new JsonObject[noOfObjects to be iterated]

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.
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

Categories