Escaping the whole object array with JQuery - javascript

Can I escape array of object with Jquery ? I got error SyntaxError: illegal character when I retrieving Java.Util.List object. At my Controller class , I pass object array as like that..
Map<String, List<User>> result = new HashMap<String, List<User>>();
// getting datas from database
List<User> datas = new ArrayList<User>();
datas = dao.get...................
result.put("data",datas);
When I gettting it from my JSP as
<script type="text/javascript">var results = ${result.data};</script>
I got syntaxError.So, I googling it and I assume my object array contains illegal characters and I should escape them. (This may my opinion ). So , I tried to escape charaters of this object array but I don't know how to do it ? I tried as like these..
console.log(JSON.stringify(${result.data}));
console.log(${result.data}.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
console.log(${result.data}.replace(/[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g, ""));
console.log($.grep( ${result.data}, function(e){ return e.id == id; }));
console.log(JSON.parse(${result.data}));
All produce same error.
Now I am still trouble in it . Any suggestion would be appreciated. My main point to get is I want to use my object array without any error.Please help me.

What ${result.data} does is basically output datas.toString(). It depends on the structure of the User object what the output will be.
The best thing to do is using a Java Objects to JSON serializer like Gson or Jackson and write a Servlet to output the data as JSON.
Gson
Gson gson = new Gson();
String json = gson.toJson(datas);
See Gson user guide.
Jackson
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(datas);
See Jackson documentation.
Servlet
In your Servlet you can output the generated JSON with the correct content type:
response.setContentType("application/json; charset=UTF-8");
try (OutputStream os = response.getOutputStream())
{
os.write(json.getBytes());
os.flush();
}
This way you can simply load your data using jQuery.getJSON().

Now I am fine with that..
<c:set var="results" value="${result.data}" />
<script type="text/javascript">
var results = jQuery.makeArray("${results}");
alert(results.length);
alert("${results[0].attributeName}");
</script>

Related

Sending a Jackson converted string or JSON object to HTML page using thyemeleaf

I'm trying to send a JSON object to a property in javascript using thymeleaf, but when the value is received, all the quotes are converted to ".
In my POJO, I have the following method:
public class MyObject {
public String toJSON() throws IOException {
StringWriter result = new StringWriter();
if (this.getCaseRegistrations().size() > 0) {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(result, this.caseRegistrations);
}
return result.toString();
}
And elsewhere, that class is created and ready to use and sent to the ModelAndView in the Spring controller:
mav.addObject("myObject", myObject);
In my html page, I have the following:
<script type="text/javascript">
$(document).ready(function() {
let registrations = [[ ${myObject.toJSON()} ]]
console.log(registrations);
});
Unfortunately, when this runs, javascript fails on the assignment with a complaint about &. Looking at the Source, I see the following:
let registrations = [{"prop1":"val1", ...}];
When I look at the string on the java side (in debug mode), the value looks correct
[{ "prop1": "val1", ...}]
I've tried various things, such as let registrations = '[[ ${myObject.toJSON()} ]]' (using the backquote here) and let registrations = decudeURI[[ ${myObject.toJSON()} ]]) and [# th:utext="${myObject.toJSON()}"/];. That last attempt (with th:utext), failed completely.
What is the proper way to convert a POJO to a JSON and the assign it to a variable in javascript on an html page? (Java-Spring-Thymeleaf)
i dont have much experience in this tech but i can help you to give scenario is that
Capture the json data before sending to js.
then use something like strrplace() i dont if you know some another function [http://w3schools.com/php/func_string_str_replace.asp] look ta here it will replace all the brackets. see first argument will be what you want to replace and second will be with what you want replace .
in my case it was like,
$user=str_replace("'[',']','{','}'",(my json variable data));

Javascript reads my date String as number, when I pass my data with ModelAndView(Spring)

I use Spring Boot framework and Thymeleaf to build my program.
When I pass my date String with ModelAndView in my controller as follows:
#RequestMapping(value = "/search")
public ModelAndView search() {
ModelAndView view = new ModelAndView("exchangerate");
List<String> timeList = new ArrayList<>();
timeList.add("2017/07/21");
timeList.add("2017/07/24");
timeList.add("2017/07/25");
timeList.add("2017/07/26");
view.addObject("timeList",timeList);
return view;
}
And
<script>
var yAxis = [[${timeList}]];
var yAxis2 = ['2017-07-21', '2017-07-24', '2017-07-25', '2017-07-26'];
console.log(yAxis);
console.log(yAxis2);
</script>
What I see in console is
[13.721088435374151, 12.005952380952381, 11.525714285714287, 11.082417582417584]
["2017-07-21", "2017-07-24", "2017-07-25", "2017-07-26"]
So I guess it reads yAxix as number.
What can I do if I want to use yAxis as String or Date format?
I believe using:
<script th:inline="javascript">
will fix this. It should output it as a list of quoted strings.
It is fairly simple to understand why this happens.
When you send it to the JavaScript for processing, JSON.parse actually interprets your dates as (2017/07)/21, which gets evaluated to the floating decimals you see. This implies that your dates are not getting converted into strings for JSON before being sent further.
As a remedy, either consider sending your dates wrapped in a proper date object from Spring end, or consider stringifying your dates before you send them using a JSON mapper at the Spring end.

convert map of custom object to json object?

In java , i have a hashmap like below
Map<String, List<Employee>> = new HashMap<String, List<Employee>>();
I need to convert the above map to json object
What I tried:-
used jsonObject instead of HashMap and JsonArray instead of list
com.amazonaws.util.json.JSONObject jsonObject = new com.amazonaws.util.json.JSONObject();
com.amazonaws.util.json.JsonArray empList = new JsonArray();
empList.add(empObject)
jsonObject.put("some String", empList);
Then add jsonObject in request attribute
request.setAttribute("empMap", jsonObject.toString() );
but when i retrieve it in javascript i get the value of jsonObject
{emp_10:[com.val.Emp#4b7b4bc5]}
As you can see above i get the value com.val.Emp#4b7b4bc5 not its properties why so ?
Also Is there a better way where i can convert the hashmap of custom object i.e Map<String, List<Employee>> to json object without using
jsonObject instead of HashMap and JsonArray instead of list?
I am using already below libraries in my project and open to use any new one if required
Jettison Library (org.codehaus.jettison.json.JSONObject)
json-lib(net.sf.json.JSONObject)
apache json library (com.amazonaws.util.json.JSONObject)
I think you need to have an additional helper function at java end
public JSONObject asJSON(Employee employee) {
ObjectMapper mapper = new ObjectMapper();
return new JSONObject(mapper.writeValueAsString(employee));
}
and in place of adding empObject in following, add the updated value asJSON(empObject)
empList.add(empObject)
Additionally, remove .toString()
request.setAttribute("empMap", jsonObject.toString());

Passing (and parsing!) JSON objects through MVC4

I'm confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript.
I'm also not sure if I'm correctly parsing the JSON objects at the right points...
My controller is returning a PartialView with a json object ("Variables" is a list of data e.g. Id=2012, Name=BillyJoel, Value="£2,000"):
public ActionResult JavascriptConstants() {
var variables = Service.Obtain<VariableService>().All().ToList();
var json = new JavaScriptSerializer().Serialize(variables);
return PartialView("JavascriptConstants", json);
}
My View then makes this data available to my scripts by creating this variable:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object?
I've tried changing my JS to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I'm assuming when it hits the "I" of "Id).
Any help much appreciated, thanks.
I found the issue:
The issue was the use of JavaScriptSerializer().Serialize(foo) as this was creating a JSON object that contained newlines and tabs instead of replacing them with \n and \t.
$.parseJSON() cannot handle newlines and so throws up unexpected token error.
This was corrected by importing the JSON.NET package and using :
var json = JsonConvert.SerializeObject(variables);
This passed a JSON object with newlines and tabs replaced with \n's and \t's. Which can then be made accessible to the View using:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
and finally in the script using:
var variableList = $.parseJSON(mvcListOfVariablesInDB)
Hope this helps someone else one day...

Passing Array from Activity to Javascript

I know there a couple of threads similar to this one but they dont actually answer the above question.
Firts question: is it true that only primitives can be passed? (String, boolean,...)
Second question: if it is so. I have an array of String in my activiy and i need it to fill a html table in my WebView and apparently i need to use Javascript interface to do so. So the question is: How can i do that? Do I need to create a string in my activity, pass it to JS and once there recreate the array?
You could use JSON as format for your data. A simple way would be to use a lib like GSON http://code.google.com/p/google-gson/ which makes it easy to convert your ArrayList with own object-types to Strings.
Send that to your WebView via the Javascript-interface and use JSON.parse(Stringname) in JS to recreate your Array.
Best wishes,
Tim
Your option is to expose the method using strings and then you can use the JSONObject or JSONArray to parse the string and use it accordingly.
Here is what I did.
#JavascriptInterface
public void passJSON(String array, String jsonObj) throws JSONException
{
JSONArray myArray = new JSONArray(array);
JSONObject myObj = new JSONObject(jsonObj);
...
}
where array is '["string1","string2"]' and jsonObj is '{attr:1, attr2:"myName"}'
"Do I need to create a string in my activity, pass it to JS and once there recreate the array?"
That's the way i resolved it in my case ; i appended a special character to each item in the list while building up the string and later split it up in JS.
var strings = get.list(); // long string from activity.
var item1 = strings.split("=")[0];
var item2 = strings.split("=")[1];
....
Or you could go for a library

Categories

Resources