将 Java 列表转换为 Javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21048962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:11:36  来源:igfitidea点击:

Convert Java List to Javascript Array

javajavascriptandroidarrayslist

提问by Prabhu

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:

爪哇:

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 中使用吗?

采纳答案by bbuecherl

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:

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. JSONis 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 fetchFriendsin Java but its called parseFriendsin Javascript, I renamed them to fetchFriends

我遇到的小事:你fetchFriends在 Java中使用但它parseFriends在 Javascript 中调用,我将它们重命名为fetchFriends

回答by Rathish

Its just an example, First add javascript interface. It will be a bridge between javascript and java code. webView.addJavascriptInterface(new JSInterface(), "interface");

它只是一个例子,首先添加javascript接口。它将成为 javascript 和 java 代码之间的桥梁。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. create a class JSInterace and define a method setPageCount(int a). The script will return a value, and you can use that value in your java method

interface是java和javascript的共同关键字。创建一个类 JSInterace 并定义一个方法 setPageCount(int a)。该脚本将返回一个值,您可以在 java 方法中使用该值

回答by Neeraj Krishna

You can use the Google Gson library (http://code.google.com/p/google-gson/) to convert the Java List Object to JSON. Ensure that the right fields are set like ID, UserName, FirstName, etc and on the java script side that same code would work.

您可以使用 Google Gson 库 ( http://code.google.com/p/google-gson/) 将 Java 列表对象转换为 JSON。确保设置了正确的字段,如 ID、用户名、名字等,并且在 java 脚本端相同的代码可以工作。

回答by NarendraSoni

Use GSONto convert java objects to JSONstring, 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(list)会给你

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

[{"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.

现在您可以使用JSON.parse()将 JSON 反序列化为 Javascript 对象。

回答by xild

You can use Gson Library.

您可以使用 Gson 库。

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

回答by Fco P.

Use Hymanson. You'll need to add an " @JsonProperty" annotation to every property of your POJOs you want to pass, then do something like this:

使用Hyman逊。您需要为要传递的 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+")");
        }

回答by Siva Tumma

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

我不知道为什么没有提到关于jaxb. 我只是想jaxb会很适合这种类型的问题......

For a sample style of annotated jaxbclass, 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 marshaleither in xmlor a json. After you get a jsonto the client, you can do a var myArray = JSON.parse(response);...

你会的东西,在这些列表数据会让你marshal无论是在xmljson。在你得到json客户后,你可以做一个var myArray = JSON.parse(response);......

回答by Cody A. Ray

Although I typically advocate using something like GSON or Hymanson 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 或 Hymanson 之类的东西来为您进行 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 GraphUserto 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:

如果您愿意,您显然可以制定一种toJSON()方法GraphUser来放置逻辑。或者使用可注入的 json 帮助程序库而不是静态方法(我会)。或任意数量的其他抽象。许多开发人员更喜欢将模型对象的表示分离到他们自己的对象中,包括我自己。就个人而言,如果我想避免依赖关系,我可能会像这样建模:

  • 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.
  • 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>>它可以进行类型检查或使用访问者模式或其他方法来确定表示此类对象集合的最佳方式。

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.

在此过程中,我相信您会发现一些重复的代码可以提取到超类或复合类中,尤其是当您开始以这种方式对集合编组器进行建模时。尽管这可能会变得非常冗长(而且乏味),但它在资源受限的环境中特别有效,在这种环境中,您希望限制所依赖的库的数量。