简体   繁体   English

如何在Java中将List转换为Json

[英]How to convert List to Json in Java

How to convert generic list to json in Java.I have class like this.. 如何在Java中将通用列表转换为json。我有这样的类..

public class Output
{
    public int Keyname { get; set; }
    public Object  outputvalue{ get; set; }  //outvalue may be even a object collection
}

List<Output> outputList = new List<Output>();

I want to convert outputList into json in Java.After converting i will send it to client. 我想在Java中将outputList转换为json。转换后我将它发送给客户端。

Use GSON library for that. 使用GSON库。 Here is the sample code 这是示例代码

List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");

String json = new Gson().toJson(foo );

Here is the maven dependency for Gson 这是Gson的maven依赖

<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.2</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

Or you can directly download jar from here and put it in your class path 或者你可以直接从这里下载jar并将它放在你的类路径中

http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q= http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=

To send Json to client you can use spring or in simple servlet add this code 要将Json发送到客户端,您可以使用spring或简单的servlet添加此代码

response.getWriter().write(json); 。response.getWriter()写(JSON);

You need an external library for this. 你需要一个外部库。

JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);

Google GSON is one of such libraries 谷歌GSON就是这样的图书馆之一

You can also take a look here for examples on converting Java object collection to JSON string. 您还可以在此处查看有关将Java对象集合转换为JSON字符串的示例。

Look at the google gson library. 看看谷歌gson库。 It provides a rich api for dealing with this and is very straightforward to use. 它为处理这个问题提供了丰富的API,并且非常简单易用。

Try this: 试试这个:

public void test(){
// net.sf.json.JSONObject, net.sf.json.JSONArray    

List objList = new ArrayList();
objList.add("obj1");
objList.add("obj2");
objList.add("obj3");
HashMap objMap = new HashMap();
objMap.put("key1", "value1");
objMap.put("key2", "value2");
objMap.put("key3", "value3");
System.out.println("JSONArray :: "+(JSONArray)JSONSerializer.toJSON(objList));
System.out.println("JSONObject :: "+(JSONObject)JSONSerializer.toJSON(objMap));
}

you can find API here . 你可以在这里找到API。

For simplicity and well structured sake, use SpringMVC. 为了简单和结构良好,使用SpringMVC。 It's just so simple. 这很简单。

@RequestMapping("/carlist.json")
public @ResponseBody List<String> getCarList() {
    return carService.getAllCars();
}

Reference and credit: https://github.com/xvitcoder/spring-mvc-angularjs 参考和信用: https//github.com/xvitcoder/spring-mvc-angularjs

download java-json.jar from Java2s then use the JSONArray constructor 从Java2s下载java-json.jar然后使用JSONArray构造函数

List myList = new ArrayList<>();    
JSONArray jsonArray = new JSONArray(myList);
System.out.println(jsonArray);

jackson provides very helpful and lightweight API to convert Object to JSON and vise versa. jackson提供了非常有用且轻量级的API,可将Object转换为JSON,反之亦然。 Please find the example code below to perform the operation 请在下面找到示例代码来执行操作

List<Output> outputList = new ArrayList<Output>();
public static void main(String[] args) {
    try {
        Output output = new Output(1,"2342");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(output);
        System.out.println(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

there are many other features and nice documentation for Jackson API. Jackson API还有许多其他功能和很好的文档。 you can refer to the links like: https://www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial .. 您可以参考以下链接: https//www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial ..

dependencies to include in the project are 要包含在项目中的依赖项

    <!-- Jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>

Use GSONBuilder with setPrettyPrinting and disableHtml for nice output. 将GSONBuilder与setPrettyPrinting和disableHtml一起使用以获得良好的输出。

String json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().
                            create().toJson(outputList  );
                    fileOut.println(json);

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

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