如何在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>();
Run Code Online (Sandbox Code Playgroud)
我想在Java中将outputList转换为json.转换后我将它发送给客户端.
cod*_*ish 108
使用GSON库.这是示例代码
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
或者你可以直接从这里下载jar并将它放在你的类路径中
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
要将Json发送到客户端,您可以使用spring或简单的servlet添加此代码
.response.getWriter()写(JSON);
Rah*_*hul 12
你需要一个外部库.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Run Code Online (Sandbox Code Playgroud)
谷歌GSON就是这样的图书馆之一
您还可以在此处查看有关将Java对象集合转换为JSON字符串的示例.
jackson 提供了非常有用和轻量级的 API 来将 Object 转换为 JSON,反之亦然。请找到下面的示例代码来执行操作
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Jackson API 还有许多其他功能和不错的文档。您可以参考以下链接:https : //www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial ..
要包含在项目中的依赖项是
<!-- 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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
231074 次 |
最近记录: |