Display JSON Envelope on JSP - java

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

Related

Java Class parsed to JSON does not output correct Json Object

I use Java (with Quarkus) for the backend.
Vue3 for the frontend.
API and Websockets to transition data between the two.
I am building a chat message application.
So far I was able to send a message inside the backend under a JSON format, do stuff in Java with this message (which holds the message inside a MessageJson class that I have created, hence the data type is now type of MessageJson), transform it into a String, then and send it back to the frontend. I wish to transform the String in the frontend, into a Json.
Here is my function which send the message back to the front (using Websockets):
public MessageResponseForm processBackend(MessageJson messageJson) {
MessageResponseForm messageResponseForm = new MessageResponseForm();
messages(messageJson);
webSocketConfig.sendMessage("U001", messageJson.toString());
return messageResponseForm;
}
The frontend retrieve it without issue, in the String format.
But I need it back into Json format.
I use the function JSON.parse() in Vue.js but it gives me this:
Which is normal in my opinion, because I should receive something like this from the backend:
"{"toRecipient":"U002","fromSender":"U00555","messageContent":"ewww555"}" .....
But instead I got this:
"MessageJson(toRecipient=U002, fromSender=U00555, messageContent=ewww555, dateCreated=2022-9-23 14:15:57, companyName=test)"
My Class MessageJson does not seems to keep the correct Json format.
How to prevent this?
Do I need to use the #Produces annotations in Quarkus? If yes, where exactly?
I found no other method related to ToString()...
EDIT: Do I need to use the dependency GSON to do the job, or can I do this natively?

spring mvc use javascript to call and return data in this format

I bought a website template and now I'm modify the template to suit my project.
one of my question is I have a JS function in the template is hardcoded data like below:
var visitors = [
['02/2013', 1500],
['03/2013', 2600],
['04/2013', 1200],
['05/2013', 560],
['06/2013', 2000],
['07/2013', 2350],
['08/2013', 1500],
['09/2013', 50000],
['10/2013', 1300]
];
Question 1: How can I call the java code and return the result and suit to this format? Can I say above format is JSON?
Question 2: So I need to add the GET function into the JS function?
1.) JSON is a set of key value pairs. For example
var DateJson={"MyArray":
[
["02/2013", 1500],
["03/2013", 2600],
["04/2013", 1200]
]};
Then you get the value of "MyArray" and get the desired value. To construct it in Java , you can use JSON API or you can do it manually as well. One of JSON documentation is here :-
http://www.json.org/javadoc/org/json/JSONArray.html
2.) You can do GET to a URL that returns desired response.
$.ajax({
url:"myURL",
type:"GET",
success:function(msg){
DateJson = msg;
},
dataType:"json"
});
The code that is there at myURL should construct the json that you need.

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.

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