Java 将 Arraylist 转换为 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20801248/
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 04:26:57  来源:igfitidea点击:

convert Arraylist into json

javajsonarraylist

提问by Prabu

please help how could we convert the below Arraylist method into Json

请帮助我们如何将下面的 Arraylist 方法转换为 Json

public ArrayList<String> helloName(String patentno)  {

    ArrayList<String> bibo = new ArrayList<String>();

    for (int row = 2; row < rowsize; row++) {
        pno = driver.findElement(
                By.xpath("//*[@id='body']/table/tbody/tr[" + row + "]/td"))
                .getText();
        bibo.add(pno);
    }
    return bibo;
}

回答by Tareq Salah

Use GSONlibrary for that. Here is the sample code

为此使用GSON库。这是示例代码

ArrayList<String> bibo = new ArrayList<String>();
bibo.add("obj1");
bibo.add("obj2");
bibo.add("obj3");
String json = new Gson().toJson(bibo);

And this examplefrom Gson User Guide to use it on collection

以及Gson 用户指南中的这个示例,用于在集合中使用它

回答by Sujith PS

You can use org.codehaus.jettison.json.JSONArrayfor the same (Download jar).

您可以使用org.codehaus.jettison.json.JSONArray相同(下载 jar)。

Example Code :

示例代码:

   ArrayList bibo=new ArrayList();

   .....

  JSONArray ar=new JSONArray(bibo);
  String json= ar.toString();

回答by Saurabh

use
Gson gson = new GsonBuilder().create();


Gson gson = new GsonBuilder().create();

JsonArray myCustomArray = gson.toJsonTree(list).getAsJsonArray();