Java ArrayList to Javascript Array - javascript

i have a Java ArrayList and i want to send it to the javascript for another purpose.
this is my Java ArrayList
List<String> list = new ArrayList<String>();
list.add("xxx");
list.add("yyy");
....
model.addAttribute("theList", list);
and how to send the ArrayList into javascript Array?
i'm expecting this in my javascript code
<script th:inline="javascript">
var Array = ["xxx","yyy","xxx"];
</script>
i'm truly sorry for asking this type of question again, i know there's already answered questions and duplictae questions about this case, but i don't really understand the answer. maybe some JSON things or other ways.
please show me how to write the code both in java code and javascript code.
Thanks.

As mentioned in the comments, you can use a library to serialize the object as a json string. In other words, you can convert each list element to a json object node and put all the json object nodes into an array.
What a serializer does
It takes a look at your object(s) and creates a json representation out of it/them (serializes). The opposite of a serializer is a deserializer, to convert a json string into Java objects.
Why use a library
While you could do it by hand (see below), a library such as Gson as mentioned in the comments, or jackson in the open source community has been tested on a large number of test cases and will in all likelihood be robust enough for whatever your use case is.
Example with jackson
See here.
Example "do it yourself"
Your case is very simple since your list elements are strings.
// create a string builder to build the json
StringBuilder sb = new StringBuilder();
// loop over each string in the list
for (String s : list) {
// add an initial delimiter, which will be
// removed at the end
sb.append(",");
// add a beginning quote to each term
sb.append("\"");
// add the string
sb.append(s);
// close the quote
sb.append("\"");
}
if (sb.length() > 0) {
// if there was at least one element
// in the list, remove the initial comma
sb.deleteCharAt(0);
}
// add a left square bracket
sb.insert(0, "[");
// add a right square bracket
sb.append("]");
// your string, for example
// ["one","two","three"]
String json = sb.toString();
Going back to "why use a library", the above code doesn't account for a lot of possibilities, the most obvious of which, if one of the strings in the list contains a " character it will mess everything up. Note that there are many ways to handle the above.
I hope that helps.

Scriptlet tag allows to write Java code into JSP file.
Syntax
<% java code %>
Here <%%> tags are scriplets tag and within it, we can place java code.
`<% List<String> strList = new ArrayList<String>();
strList.add("xxx");
strList.add("yyy");
strList.add("zzz");%>`
var jsArray = [<% for (int i = 0; i < strList.size(); i++) { %>"<%= strList.get(i) %>"<%= i + 1 < strList.size() ? ",":"" %><% } %>];
The output will be
var jsArray = ["xxx","yyy","zzz"];

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));

Java ArrayList to javascript

Having spent a week trying to get a java ArrayList to 'appear'in javascript (in the same jsp) I am at the point of giving up as
none of the supposed 'examples' in various forums works.
As a last resort I attempted this with JSON, but that doesn't work either.
If this is an impossibility then can someone confirm that?
There is a SQL select followed by a c:set (in JSTL) followed by a java ArrayList (in a java scriplet in the same jsp) inside a c:forEach loop.
This is working properly and the output is 1 6 3 2 1 7 etc
There is also a StringBuffer which adds commas,
this is also working properly and the output is 1,6,3,2,7 etc.
I now want that same array, in the same format, to appear in javascript
(in the same jsp) so I can use it for dynamic arrays in chart.js.
Hence my 'final' attempt' to use JSON.
It doesn't matter whether the JSON is after the ArrayList or after the StringBuffer as long as I can get the array into javascript.
However the JSON code produces what appears to be each element of the array in its own square brackets (jsonQuantities = [1] jsonQuantities=[6] etc
<c:set var="quantity" value="${row.Quantity}" />
<c:set var="zone" value="${row.zone}" />
<%
//produce array
ArrayList quantities= new ArrayList();
quantities.add(pageContext.getAttribute("quantity"));
//convert to JSON
Gson gson = new Gson();
String jsonQuantities = gson.toJson(quantities);
out.println("jsonQuantities = " + jsonQuantities);
//add commas
StringBuffer thesequantities = new StringBuffer();
for(int i=0; i<quantities.size(); i++)
{
thesequantities.append(quantities.get(i));
thesequantities.append(",");
}
out.println(thesequantities.toString());
%>
</c:forEach>
Then I attempt to get the array into javascript - the JSON.parse line does nothing other than prevent any JavaScript below it from executing.
I have tried various forEach loops and so called 'conversions' to output the array
but nothing works.
<script type="text/javascript">
var myobject = JSON.parse("jsonQuantities");
document.write("the quantities are" +myobject.count);
All the examples using c:forEach (i.e. below), getParameter, getAttribute etc do not work.
var jsArray = [
<c:forEach var="item" items="${jsonQuantities}">
<c:out value="${item}"/>,
</c:forEach>
];
Does anybody have actual working code / experience of this (without using separate php, jsp's etc)?
All I need is the java ArrayList (1 6 3 2 1 7 etc) or StringBuffer (1,6,3,2,7 etc) contents 'transferred' to javascript and then output (so I can see all the elements
irrespective of what they are named or in which format they are in).
Thanks, Ralph

Sending an array with JavaScript to the next page

The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.

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

Pass IEnumerable List to javascript

I was wondering if I could pass a IEnumerable Collection into a Javascript method on the page load. So something like this...
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyAppMVC.Models.ViewModels.News.NewsIndexViewData>" %>
<div id="container">
<%= String.Format("<script type='text/javascript'>testMethod({0})</script>", Model.NewsList) %>
</div>
I realize JS is client side, just didn't know if there was any way possible to do that?
Thanks!
No, you cannot. For several reasons.
1) There is no IEnumerable in JavaScript, as you use it in .NET. There is something similar, but it is implemented completely differently. In .NET, IEnumerable just means the class provides a method, GetEnumerator(), which returns an IEnumerator (which itself only contains Current, MoveNExt, and Reset methods). In JavaScript, when you do a for iteration on an item, you are iterating over the names of its properties.
var myObj = { 'a' = 1, 'b' = 2 };
for (var name in myObj) { alert(name); } // will alert 'a', and 'b'
Even when working with JavaScript arrays, the above loop returns the index of the array element, not the actual member at that index.
2) By doing a String.Format() on your list, you wouldn't have been passing the list as an object to your JavaScript but just the ToString() result of your list. Which probably just returns "System.Collections.Generic.List`1[System.String]"
3) Unless your developing environment explicitly allows it, you can assume that passing arguments from one language into another is not going to work. Much like you can't write JavaScript inside your .NET code, you can't write .NET code in your JavaScript. These languages have different feature sets, different syntax, and are executed with completely different mechanisms - .NET is compiled, and JavaScript (generally, speaking) is interpreted (Compiled vs. Interpreted languages).
What you have to do is transform your data into a format that can be used by JavaScript. Most likely this means converting it into something called JSON. You didn't provide a lot of details as to what exactly Model.NewList is, or what your testMethod() expects as an argument. But for the sake of an example lets assume NewList is a list of strings. In that case, your JSON would look something like this:
{ 'NewList' : ['string1', 'string2', 'string3'] }
The easiest way to convert your .NET data into JSON is to use built-in libraries, such as JavaScriptSerializer:
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(Mdoel.NewList);
You can register the javascript in the code behind in the Page_Load with the following code (Note I am assuming that Model.NewsList is a string enumeration or array):
StringBuilder sb = new StringBuilder();
bool isFirst = true;
//build a comma seperated list.
foreach (string s in Model.NewsList)
{
if (isFirst)
isFirst = false;
else
sb.Append(", ");
sb.Append("'").Append(s.Replace("'", "''")).Append("'");
}
//create the javascript array
string javascript = String.Format(#"var news = [{0}];", sb);
//put the array in the generated page.
Page.ClientScript.RegisterClientScriptBlock(GetType(), "newsList", javascript);
This will put the javascript on the page accessible from other javascript functions.

Categories

Resources