manipulate the JSON object converted from a java Map - java

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;

Related

How to send hashmap <Object,boolean> as a JSON to angular controller?

I am quite new to AngularJS. I am trying to send a hashmap over to angular controller through a REST service. I am using JSONContentEncapsulator for the same. I am not sure about the syntax.
JSONContentEncapsulator<HashMap> encapsulator = new JSONContentEncapsulator<HashMap>(sampleHashmap);
The problem is my Hashmap is sent over to controller with the object converted in the string format.
Also when I try printing the key value pair on the screen using ng-repeat, it's blank.
but when I print it in my controller using forEach I am able to see the values.
Could anyone please help as to how I should achieve this so that I can retrieve the object and corresponding boolean value on the screen?
EDIT1: The json values returned by REST service in my controller look like below:
{"EventValue(eventValueId=14, eventValueDescription=Deb Basic Neg Settle-intern plus , valueClassId=ALTBASIC, resultType=CALC, creditdebitIndicator=DEBIT, sign=POSITIVE, custAccountType=INTERNAL_SETTLEMENT)":true,"EventValue(eventValueId=11, eventValueDescription=Cred Basic Neg Correction minus , valueClassId=ALTBASIC, resultType=CORP, creditdebitIndicator=CREDIT, sign=NEGATIVE, custAccountType=NA)":true}
Where EvenValue is the object which is used as key and there is corresponding boolean value with it.
As I read online. It is not possible to send Map with Object as key in JSON format.
So instead I created two arraylists out of the map and sent those as a part of a single nested list.
It works fine.

How to get an xsp value from URL link using Java

I am trying to retrieve the page name(.xsp)from the URL of the current page using Java. i have been able to accomplish the same thing with the Javascript below
context.getUrl().getSiteRelativeAddress(context).toString()
and it works but i want to get the same thing don using Java.
The best way to get SSJS variable names via Java is resolveVariable. This should work:
XSPContext context = (XSPContext) ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "context");
String pageName = context.getUrl().getSiteRelativeAddress(context).toString();
(Updated with correct syntax for second line, thanks Knut)

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

Passing Jackjson JSON object from JSP to JavaScript function

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

Categories

Resources