如何在Java中将List转换为Json [英] How to convert List to Json in Java
问题描述
如何在Java中将通用列表转换为json。我有这样的类..
How to convert generic list to json in Java.I have class like this..
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>();
我想在Java中将outputList转换为json。转换后我会将它发送给客户端。
I want to convert outputList into json in Java.After converting i will send it to client.
推荐答案
使用GSON库。以下是示例代码
Use GSON library for that. 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 );
这是Gson的maven依赖
Here is the maven dependency for Gson
<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>
或者你可以直接从这里下载jar并把它放在你的班级路径中
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
要将Json发送到客户端,您可以使用spring或简单的servlet添加此代码
To send Json to client you can use spring or in simple servlet add this code
response.getWriter()。write(json );
response.getWriter().write(json);
这篇关于如何在Java中将List转换为Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!