Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List to Json in Java

Tags:

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>(); 

I want to convert outputList into json in Java.After converting i will send it to client.

like image 802
vmb Avatar asked Jan 09 '13 05:01

vmb


People also ask

Can we convert list to JSON in Java?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

Can you convert list to JSON?

To convert a list to json in Python, use the json. dumps() method. The json. dumps() is a built-in function that takes a list as an argument and returns the json value.

Can Gson convert list to JSON?

A Gson is a library that can be used to convert Java Objects to JSON representation.

How do I convert a JSON list to Jackson?

We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.


2 Answers

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 ); 

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> 

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=

To send Json to client you can use spring or in simple servlet add this code

response.getWriter().write(json);

like image 72
code_fish Avatar answered Oct 13 '22 08:10

code_fish


You need an external library for this.

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

Google GSON is one of such libraries

You can also take a look here for examples on converting Java object collection to JSON string.

like image 39
Rahul Avatar answered Oct 13 '22 08:10

Rahul