How to parse json java object in javascript - java

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.

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.

Display JSON Envelope on JSP

I have a Spring #Controller that is taking an existing ArrayList and creating a JSON envelope. When I display the JSON Envelope in the Spring Console, I see the data that I want is in there. When I view the same JSON Envelope in FireBug in Firefox, I also see the data that I want.
I'm attempting to display the envelop on the jsp page using JavaScript, and I really have no idea how to even start.
In other modules of the code, there are areas where it's getting information from a DataBase, using YUI2 to display it with a DataTable. It also uses a JSON Envelope, and it works. I'm trying to copy this to display just the JSON text string on the JSP page. I don't know if I need to use YUI2, or if I can just use JavaScript to access the JSON Envelope.
I am brand new to Java and JSON and the Spring environment, so I don't even have any idea what sort of JavaScript syntax to use to access the JSON Envelope, much less display it. I've been Googling to find an answer, but so far most of it is above my head.
I'd appreciate any help. Thanks.
Your Question is very unclear.
If you simply want to display the text of the JSON, then you don't need to use javascript at all. Just use <c:out> to output the JSON string into the relevant part of a plain HTML page.
You would use Javascript if you wanted to generate dynamic HTML on the client side. And at that point you'd probably want the Javascript to use an XMLHttpRequest object to call to the server to request the JSON. The Javascript would then be responsible for dynamically turning that JSON response into stuff that can be displayed ... and you'd definitely be wanting a client-side JS framework to help with that.
To parse the retrieved JSON you can use $each method of jQuery
var obj = {
"Name": "Robert",
"Counrty": "USA",
"Address" : {"Apartment":"111","City":"Atlanta","State":"GA","Zip":"30005" }
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
if(typeof(value)=="object")
{
$.each( value, function( key, value ) {
alert( key + ": " + value );
});
}
});
If you have more complex JSON then you have to repet $each for each complex type as I did for Address.
Then you can use the Key value to fetch the data from the JSON object.
Working example

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

Parsing JSONObject in javascript or Jquery

Hi friends i have a java.util.Map object in Ajax method like this..
Map<String,List<String>> sm = new TreeMap<>();
List<String> str = new ArrayList<String>();
str.add("val1");
str.add("val2");
str.add("val3");
str.add("val4");
sm.put("shift1", str);
sm.put("shift2", str);
sm.put("shift3", str);
sm.put("shift4", str);
JSONObject json = new JSONObject(sm);
response.getWriter().print(json);
In run time Map elements will be increase or decrease
according to map elements I have to generate table
This is Ajax call.. I don't know how to parse that Map object and dynamically generate the table in javascript.
Please show me how.
I am just answering your question. I don't know java and also i don't understand the details you gave above. If I am wrong, I am sorry and kindly ignore it.
To parse the string to object
In the jQuery, $.parseJSON(string);
In js, JSON.parse(string);
I hope this will help U. Thanks.
var json = $.parseJSON( jsonString );
// This one wouldn't be supported in old browsers
json = JSON.parse( jsonString );
Additionally, you could, in Java, respond with the Content-Type application/json and then in the jQuery AJAX you will receive the JSON already parsed for you.
Of course this will not happen if you specifically configure your jQuery AJAX call to receive an plain text, or HTML, or other content-type response.
For more reference, see here, at the dataType setting.

How to return the original string in Java after using jquery.serialize()

I have a problem after serializing the form with jquery.
Why some text retain the html entities even after loaded to Java(Servlet)
For example I have a text & and it will return into %26 in Java.
I serialize and submit the form into Java using this..
function ajaxSubmit(frmN){
var serForm = $(frmN).serialize();
$.ajax({
type:'POST',
url:'inser',
data:{actionName : "insertField", formField : serForm},
success: function(request){
$("#reqContainer").html(request);
}
});
}
Is there a way to deserialize the html entities from java.
I guess I need first to split the & and then split the =
to get the list of field and its value, and after that the
deserialization will begin.
I'll appreciate any help.
I read some article using JSON but I don't have time to study it.
If there is an alternative way submitting all the form values via
ajax with jquery, and will get the original
value from Java please let me know.
Did you try JQuery form plugin? I remember a ajaxSubmit utility method.
http://malsup.com/jquery/form/
Otherwise you could just use URLDecoder in java. This will change your ascii character back to its original string.

Categories