简体   繁体   English

将Java List转换为Javascript数组

[英]Convert Java List to Javascript Array

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: 我的Android应用程序中有以下java代码,想要一种将Java列表转换为可在javascript中使用的数组的方法:

Java: 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: 使用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? 有些人可以帮我用Java代码创建usersObjectFromJava,以便它可以在javascript中使用吗?

Use GSON to convert java objects to JSON string, you can do it by 使用GSON将java对象转换为JSON字符串,你可以通过它来实现

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 gson.toJson(列表)会给你

[{"prop1":"value1","prop2":2},{"prop1":"value2","prop2":2},{"prop1":"value3","prop2":3}] [{ “PROP1”: “VALUE1”, “PROP2”:2},{ “PROP1”: “VALUE2”, “PROP2”:2},{ “PROP1”: “值3”, “PROP2”:3}]

Now you can use JSON.parse() , to deserialize from JSON to Javascript Object. 现在,您可以使用JSON.parse()将JSON反序列化为Javascript对象。

I would assume doing this: 我会假设这样做:

Java: 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: JavaScript的:

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

You will have to change the Java-Code a bit (ie using public getters or add more/less information to the JSONObjects . JSON is included in Android by default, so no external libraries are necessary. 您将不得不稍微更改Java代码(即使用公共getter或向JSONObjects添加更多/更少的信息。默认情况下, JSON包含在Android中,因此不需要外部库。

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 小的事情我碰到:你在哪里使用fetchFriends Java编写,但其所谓的parseFriends在Javascript中,我改名为他们fetchFriends

You can use Gson Library. 您可以使用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 http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html

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: 您需要在要传递的POJO的每个属性中添加“@JsonProperty”注释,然后执行以下操作:

    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+")");
        }

I am not sure why no answer mentioned about jaxb . 我不确定为什么没有提到关于jaxb答案。 I am just thinking jaxb would be a good fit for this type of problems... 我只是觉得jaxb非常适合这类问题......

For a sample style of annotated jaxb class, please find this. 有关带注释的jaxb类的示例样式,请找到它。

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 . 您将把数据填充到这些列表中,然后您将以xmljson marshal After you get a json to the client, you can do a var myArray = JSON.parse(response); 获得json到客户端后,可以执行var myArray = JSON.parse(response); ... ...

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. 虽然我通常主张使用像GSON或Jackson这样的东西来为你做JSON转换,但如果你处于一个有限的环境(比如Android)并且不想捆绑一堆依赖项,那么它很容易推出自己的转换。

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. 显然,如果您愿意,可以在GraphUser上创建一个toJSON()方法来放置逻辑。 Or use an injectable json helper library instead of static methods (I would). 或者使用可注入的json助手库而不是静态方法(我愿意)。 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 Marshaller<F,T>使用方法T marshall(F obj)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. class GraphUserCollectionMarshaller implements JsonMarshaller<Collection<GraphUser>> ,它可以进行类型检查或使用访问者模式或其他东西来确定表示这种类型的对象集合的最佳方式。

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. 虽然这可能变得非常冗长(并且冗长乏味),但它在资源受限的环境中尤其有效,在这种环境中,您希望限制依赖的库的数量。

You can use the Google Gson library ( http://code.google.com/p/google-gson/ ) to convert the Java List Object to JSON. 您可以使用Google Gson库( http://code.google.com/p/google-gson/ )将Java列表对象转换为JSON。 Ensure that the right fields are set like ID, UserName, FirstName, etc and on the java script side that same code would work. 确保将正确的字段设置为ID,UserName,FirstName等,并在java脚本端设置相同的代码。

Its just an example, First add javascript interface. 它只是一个例子,首先添加javascript界面​​。 It will be a bridge between javascript and java code. 它将成为javascript和java代码之间的桥梁。 webView.addJavascriptInterface(new JSInterface(), "interface"); webView.addJavascriptInterface(new JSInterface(),“interface”);

In javascript you can add like this, 在javascript中你可以像这样添加,

     "window.interface.setPageCount(pageCount1);"

The interface is a keyword in common between java and javascript. 该接口是java和javascript之间的共同关键字。 create a class JSInterace and define a method setPageCount(int a). 创建一个JSInterace类并定义一个方法setPageCount(int a)。 The script will return a value, and you can use that value in your java method 该脚本将返回一个值,您可以在java方法中使用该值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM