Convert Java List to Javascript Array

31,279

Solution 1

I would assume doing 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 change the Java-Code a bit (i.e. using public getters or add more/less information to the JSONObjects. JSON is included in Android by default, so no external libraries are necessary.

I hope i understood your problem.

Small thing i came across: you where using fetchFriends in Java but its called parseFriends in Javascript, I renamed them to fetchFriends

Solution 2

Use GSON to convert java objects to JSON string, you can do it by

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

Solution 3

Although I typically advocate using something like GSON or Jackson to do JSON conversions for you, its pretty easy to roll your own if you're in a limited environment (like Android) and don't want to bundle a bunch 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();
  }
}

You could obviously make a toJSON() method on GraphUser to put the logic if you prefer. Or use an injectable json helper library instead of static methods (I would). Or any number of other abstractions. Many developers prefer to separate representation of model objects into their own object, myself included. Personally, I might model it something like this if I wanted to avoid dependencies:

  • interface Marshaller<F,T> with 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 could do type-checking or use the visitor pattern or something to determine the best way to represent this type of collection of objects.

Along the way, I'm sure you'll find some repeated code to extract to super- or composite- classes, particularly once you start modeling collection marshallers this way. Although this can get to be pretty verbose (and tedious), it works particularly well in resource-constrained environments where you want to limit the number of libraries on which you depend.

Solution 4

Use Jackson. You'll need to add an " @JsonProperty" annotation to every property of your POJOs you want to pass, 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+")");
        }

Solution 5

I am not sure why no answer mentioned about jaxb. I am just thinking jaxb would be a good fit for this type of problems...

For a sample style of annotated jaxb class, 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 stuff your data in these lists and you will marshal either in xml or a json. After you get a json to the client, you can do a var myArray = JSON.parse(response);...

Share:
31,279
Prabhu
Author by

Prabhu

Updated on July 07, 2020

Comments

  • Prabhu
    Prabhu almost 4 years

    I have the following java code in my Android application and wanted a way to convert the 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;
            }
        }
    

    Could some help me with the Java code to create the usersObjectFromJava so that it can be used in javascript?

  • Prabhu
    Prabhu over 10 years
    Currently testing this out, will let you know how it goes!
  • Prabhu
    Prabhu over 10 years
    This worked. I had to do this in javascript to make it work: var users = JSON.parse(JSON.stringify(userObjectsFromJava));
  • FIFA oneterahertz
    FIFA oneterahertz almost 8 years
    @bbuecherl I am facing similar type of issue with JSON.Can you figure it out please?? stackoverflow.com/questions/37945432/…