Passing Jackjson JSON object from JSP to JavaScript function - java

I have a JSON String stored in a database. In one of my JSP pages, I retrieve this string, and I want to be able to pass the String or the JSON object into Javascript function. The function is simply this for test purposes
function test(h){
alert(h);
}
Now I can retrieve the JSON string from the database fine, I have printed it out to the screen to ensure that it is getting it, however when I pass it in like this
<input type="button"
name="setFontButton"
value="Set"
class="form_btn_primary"
onclick="test('<%=theJSON%>'); return false;"/>
Nothing happens. I used firebug to check what was wrong, and it says there is invalid character.
So I then tried passing in the JSON object like so
Widget widg = mapper.readValue(testing.get(0), Widget.class);
Then pass in it
onclick="test('<%=widg%>'); return false;"/>
Now this will pass in without an error, and it alerts the object name, however I am unable to parse it. Object comes in like with the package name of where the widget class is stored like so
com.package.mode.Widget#ba8af9
I tried using Stringify, but that doesn't seem to work on this Jackson JSON object.
After all that failed, I tried a last resort of taking the String from the database, and encoding it in base64. However, this too fails if I do this
String test = Base64.encode(theString);
and pass that in. However if I do that, print it out to the screen, then copy what is printed out, and send that through it works, so don't quite understand why that is.
So could someone please tell me what I am doing wrong. I have tried soo many different solutions and nothing is working.
The JSON String is stored in database like this
{
"id":1,
"splits":[
{
"texts":[
{
"value":"Test",
"locationX":3,
"locationY":-153,
"font":{
"type":"Normal",
"size":"Medium",
"bold":false,
"colour":"5a5a5a",
"italics":false
}
}
]
}
]
}
Would be very grateful if someone could point me in the direct direction!!
Edit:
Incase anyone else has same problem do this to pass the JSON from JSP to the JS function
<%=theJSON.replaceAll("\"", "\\\'")%>
That allows you to pass the JSON in,
then to get it back in JavaScript to normal JSON format
theJSON = theJSON.replace(/'/g,'"');
Should work fine

I think the combination of double quotes wrapping the onclick and the ones in your JSON may be messing you up. Think of it as if you entered the JSON manually -- it would look like this:
onclick="test('{ "id":1, "splits":[ { "texts":[ { "value":"Test", "locationX":3, "locationY":-153, "font":{ "type":"Normal", "size":"Medium", "bold":false, "colour":"5a5a5a", "italics":false } } ] } ] }'); return false;"
and the opening double quote before id would actually be closing the double quote following onclick= (You should be able to verify this by looking at the page source). Try specifying the onclick as:
onclick='test(\'<%=theJSON%>\'); return false;'

You can follow the following steps
Fetch the jon string
Using the jackson or any other JSON jar file , convert the json string to json array and print the string using out.println.
Call this jsp which prints the json string
check in the firebug , you will be able to see your json .
If the Json string does not print , there can be some problems in your json format.
this is a good website for json beautification , http://jsbeautifier.org/ , really makes the string simple to read .
Thanks
Abhi

Related

Using JsonPath to parse JSON String recursively

I'm trying to parse a given JSON in String format, for example:
{
"id": "indeed",
"interaction_data":
"{\"data\":\"{\\\"something\\\":\\\"blabla\\\"}\",\"somethingElseNotNested\":\"Indeed\"}"
}
I'm working with Kotlin, and I called JsonPath.parse on the value above, the problem is, interaction_data is parsed as a String, instead of it being treated as a JSON as well.
So when I call read("$.interaction_data.data.something") it gives me an error, since interaction_data is treated as a String, instead of an object.
Any way around this? (other than parsing this part separately, I need to handle this generically).
Thanks!
Json interaction_data property is triple stringifyied. Why you don't try this
var jsonObject=..your json;
var jsonParsed=JSON.parse(jsonObject.interaction_data);
jsonParsed.data=JSON.parse(jsonParsed.data);
JsonObject.interaction_data=jsonParsed;
result
{
"id":"indeed",
"interaction_data":{"data"{"something":"blabla"},"somethingElseNotNested":"Indeed"}
}

How to check value of two fields in URL?

Hello guys I have one url for my which is connected through id,
here I am using user_login_id and response is look like this..
{"interestreceived":[{"received_detail_id":2783,"interest_id":1288,"name":"Monali Patel","profile_id":"GM453843",
"image":"","cast":"Not Willing to specify","age":"24","location":"","user_status":"Accept"}]}
Here I have received_detail_id in above JSON,,
now in my next JSON Response
here I am using both ids,and in my code I am using put extra and get extra to pass values
String matchId=this.getIntent().getStringExtra("received_detail_id");
String Id=this.getIntent().getStringExtra("user_login_id");
USER URL:
USER_URL="http://mywebsitename.com/webservice/interestreceiveddetail?version=apps&received_detail_id="+matchId+"&user_login_id="+Id;
Is this right way to do?because I am not getting output
check this it will give you way to how to use putextra and getextra How to use putExtra() and getExtra() for string data

manipulate the JSON object converted from a java Map

Inside my action I've computed a json object from a map and I get:
{"angleEqual(angle(a,d,c),angle(a,e,b)).":{"allLinesId":"['DA','CD','AE','BE']","numberOfLinesWithinAGroup":2}}
When it comes to the front end it looked fine under the chrome debugging console, however, (driving me mad!!) how do I get the content of the value under the attribute of allLinesId and display, I thought it should be straightforward to do:
var object= data.angleEqual(angle(a,d,c),angle(a,e,b)).;
object.allLinesId;
object.display;
Not worked out as a solution, thanks a lot if anyone can help.
Try the bracket notation.
var object = data['angleEqual(angle(a,d,c),angle(a,e,b)).'];
object.allLinesId;
object.display;

creating array in javascript from array object pass in by request.setAttribute in servlet

i'm trying to create a dynamic photo gallery which retrieve the photo's location from mySQL. Store the location to a photo object under the name 'private String location;'
There will be an ArrayList to hold all the different photos. After, the servlet will forward to a jsp page
request.setAttribute("list", list);
request.getRequestDispatcher("car.jsp").forward(request, response);
i have a java script for the photo gallery that takes in an array of, ["path_to_image", "optional_link", "optional_linktarget", "optional_textdescription"].
imagearray: [
["path_to_image", "optional_link", "optional_linktarget", "optional_textdescription"],
["a.jpg", "www.a.com", "", ""]
],
I would like to retrieve the location from the object in the list passed in from the servlet and convert it into the imagearray for my photo gallery to work.
I'm quite new to javascript and i've been looking around for similar example or tutorial but i couldn't find any relevant ones. Please help me out, thank you so much for your time.
what i get from your question is photo is an object of a class and location is a member variable of that class.
request.setAttribute("list", list);
request.getRequestDispatcher("car.jsp").forward(request, response);
is this list is a Arraylist of photo object or location member variable.
also you are setting attribute in java and you want that list to hold by javascript.
then in that case you can check JSON for holding your java object and to convert into javascript object.
you will get your string in JSON similar to
{imagearray:[{"path_to_image":"path_to_image","optional_link":"optional_link","optional_linktarget":"optional_linktarget","optional_textdescription"}]}
What you want to do can be simply achieved by the following sequence:
Get results from a database.
Create JSON object.
Set that object as request attribute.
Assign JSON to a JavaScript variable.
Now, let's carry on doing that list.
Get results from database
You should have a method of type getPhotoList() that returns List<Photo>. I suppose that your Photo class has the fields you'd like to export to JavaScript. In the end, you'll have List<Photo> photos initialized.
Create a JSON object
You can of course do that on your own, but a much better idea is to employ a specialized library that converts a java object to a JSON object. For example, you could use Gson library, which is a known library for that type of conversions. In the end, you'll have a JSON object, by calling String photosJSON = new Gson().toJson(photos);.
Set the JSON as a request attribute and perform a forward
Standard operation here.
request.setAttribute("photos", photosJSON);
request.getRequestDispatcher("car.jsp").forward(request, response);
Assign JSON to a JavaScript variable
In your JSP code, within a <script> block, have the following line:
var photosJS = JSON.parse(${photos});
Finally, you'll have a JS variable photosJS with a list you got from the database.

Workaround on Scraping HTML by diving into js source code

I learn about jSoup recently and would like to dive more into it. However, I have met obstacle handling webpages with javascript (I have no knowledge in js, yet :/).
I have read that htmlunit would be the correct tool to perform webbrowser actions, but I figured out that I would need no knowledge in js if I can find out the JSON object obtained in the webpage using the javascript.
For example, this page:
among the source files, one of them is tooltips.js. In this file, variable rgNeededFeeds is generated and called in method LoadHeropediaData(), which is the method to generate the whole URL link for getting the json object.
URL = URL + 'jsfeed/heropediadata?feeds='+strFeeds+'&v=3633666222511362823&l=english';
I could not get my mind on what is actually strFeeds. I have tried various combinations but it doesn't work (it returned an empty array...). Or, my guess is totally off?
What I actually need is the data it displays on top when you click on one of the "items". The info in the "hover" would do too, but it lack the "recepi" info. And I'm presuming that by getting the json object from the full URL above, well, basically all data infos should be in that json.
Anyways, this is only based on what I understand from staring at those source files for hours. Do correct me if I'm wrong. (I'm in Java by the way)
**p/s: I would also like to take this opportunity to express my thanks to Balusc, he has been everywhere when I have doubts on jSoup. :>*
strFeeds is nothing but one of these two strings : itemdata or abilitydata
You can find this in tooltips.js at line 38-45
var rgNeededFeeds = [];
$.each( [ 'item', 'ability' ],
function( i, ttType ){
icons = GetIconCollection( ttType );
if ( icons.length ){
rgNeededFeeds.push( ttType+'data' );
//..............
}
}
)
ttType is the value of an iteration over the array [ 'item', 'ability' ] which concatenated with the string data is pushed into the array rgNeededFeeds
The function LoadHeropediaData is called at the end of the function above with rgNeededFeeds as parameter :
LoadHeropediaData( rgNeededFeeds );
Aside note : If you begin to start scraping websites, learning javascript will be MANDATORY.
NOTE : you're right, the JSON contains all the information needed...

Categories

Resources