Convert Java List to Javascript Array

I have the following Java code in an Android application and I need a way to convert a Java list to an array that can be used in javascript:

Java:

public void onCompleted(List<GraphUser> users, Response response) { for(int i = 0; i < users.size(); i++) { //add to an array object that can be used in Javascript webView.loadUrl("javascript:fetchFriends(arrObj)"); } } 

Javascript:

  //this is how I want to be able to use the object in Javascript function parseFriends(usersObjectFromJava){ var users = []; for (var i = 0; i < usersObjectFromJava.length; i++) { var u = { Id: usersObjectFromJava[i].id + "", UserName: usersObjectFromJava[i].username, FirstName: usersObjectFromJava[i].first_name, LastName: usersObjectFromJava[i].last_name, }; users[i] = u; } } 

Can someone help me with Java code to create userObjectFromJava so that it can be used in javascript?

+6
source share
8 answers

I would do this:

Java:

 public void onCompleted(List<GraphUser> users, Response response) { JSONArray arr = new JSONArray(); JSONObject tmp; try { for(int i = 0; i < users.size(); i++) { tmp = new JSONObject(); tmp.put("Id",users.get(i).id); //some public getters inside GraphUser? tmp.put("Username",users.get(i).username); tmp.put("FirstName",users.get(i).first_name); tmp.put("LastName",users.get(i).last_name); arr.add(tmp); } webView.loadUrl("javascript:fetchFriends("+arr.toString()+")"); } catch(JSONException e){ //error handling } } 

JavaScript:

 function fetchFriends(usersObjectFromJava){ var users = usersObjectFromJava; } 

You will have to modify the Java code a bit (i.e. use public getters or add more / less information to JSONObjects . JSON enabled in Android by default, so external libraries are not needed.

I hope I understand your problem.

The little thing I came across: you use fetchFriends in Java, but it was called parseFriends in Javascript, I renamed them to fetchFriends

+5
source

Use GSON to convert Java objects to JSON string, you can do this with

 Gson gson = new Gson(); TestObject o1 = new TestObject("value1", 1); TestObject o2 = new TestObject("value2", 2); TestObject o3 = new TestObject("value3", 3); List<TestObject> list = new ArrayList<TestObject>(); list.add(o1); list.add(o2); list.add(o3); 

gson.toJson (list) will provide you

[{"prop1": "value1", "prop2": 2}, {"prop1": "value2", "prop2": 2}, {"prop1": "value3", "prop2": 3}]

Now you can use JSON.parse () to deserialize from JSON to Javascript Object.

+9
source

You can use the Gson Library.

 Gson gson = new GsonBuilder().create(); JsonArray jsonArray = gson.toJsonTree(your_list, TypeClass.class).getAsJsonArray(); 

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html

+1
source

Use Jackson. You need to add the annotation "@JsonProperty" for each property of your POJOs that you want to pass, and then do something like this:

  String respStr = ""; for(Object whatever: MyList) { JSONObject dato = new JSONObject(); dato.put("FirstField", whatever.SomeData()); dato.put("SecondField", whatever.SomeData2()); StringEntity entity = new StringEntity(dato.toString()); post.setEntity(entity); webView.loadUrl("javascript:fetchFriends("+entity+")"); } 
+1
source

I am not sure why the answer was not mentioned about jaxb . I just think jaxb would be well suited for this type of problem ...

For a jaxb annotated class style sample, please find this.

 import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class ResponseAsList { private List < Object > list = new ArrayList < Object > (); public ResponseAsList() { // private default constructor for JAXB } public List < Object > getList() { return list; } public void setList(List < Object > list) { this.list = list; } } 

You will fill in your data in these lists, and you will be marshal either xml or json . After you get json for the client, you can do var myArray = JSON.parse(response); ...

+1
source

Although I generally advocate using something like GSON or Jackson for JSON conversions for you, it's pretty easy to minimize it yourself if you are in a limited environment (like Android) and don't want to bind a lot of dependencies.

 public class JsonHelper { public static String convertToJSON(List<GraphUser> users) { StringBuilder sb = new StringBuilder(); for (GraphUser user : users) { sb.append(convertToJSON(user)); } return sb.toString(); } public static String convertToJSON(GraphUser user) { return new StringBuilder() .append("{") .append("\"id\":").append(user.getId()).append(",") .append("\"admin\":").append(user.isAdmin() ? "true" : "false").append(",") .append("\"name\":\"").append(user.getName()).append("\",") .append("\"email\":\"").append(user.getEmail()).append("\"") .append("}") .toString(); } } 

Obviously, you can make the toJSON() method on GraphUser to put the logic if you want. Or use an injectable json helper library instead of static methods (I would). Or any number of other abstractions. Many developers prefer to share the representation of model objects with their own object, including me. Personally, I could simulate something like this if I wanted to avoid the dependencies:

  • interface Marshaller<F,T> using the methods T marshall(F obj) and F unmarshall(T obj)
  • interface JsonMarshaller<F> extends Marshaller<String>
  • class GraphUserMarshaller implements JsonMarshaller<GraphUser>
  • class GraphUserCollectionMarshaller implements JsonMarshaller<Collection<GraphUser>> , which can perform type checking or use a visitor template or something to determine the best way to represent this type of collection of objects.

Along the way, I'm sure you will find multiple code to extract into super- or compound classes, especially after you start modeling collectible marshalers this way. Although this can be quite verbose (and tedious), it works especially well in resource-limited environments where you want to limit the number of libraries you depend on.

+1
source

You can use the Google Gson library ( http://code.google.com/p/google-gson/ ) to convert a Java list object to JSON. Make sure that the correct fields are set as ID, UserName, FirstName, etc., And on the java side the same code will work.

0
source

Its just an example: first add the javascript interface. This will be the bridge between javascript and java code. webView.addJavascriptInterface (new JSInterface (), "interface");

In javascript you can add like this:

  "window.interface.setPageCount(pageCount1);" 

An interface is a keyword between java and javascript. create the JSInterace class and define the setPageCount (int a) method. the script will return a value, and you can use that value in your java method

-1
source

All Articles