70

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.

Gabriel
  • 18,322
  • 2
  • 37
  • 44
vmb
  • 2,878
  • 15
  • 60
  • 90
  • Thats rather difficult if you just know the outputvalue is an `Object`. We can not even assume it is serializable. – Henry Jan 09 '13 at 05:45
  • assume all classes is serializable – vmb Jan 09 '13 at 05:47
  • 1
    possible duplicate of [how to convert a List of Data to json](http://stackoverflow.com/questions/8182391/how-to-convert-a-list-of-data-to-json) – Gabriel Jan 09 '13 at 05:47
  • Can you tell us what framwork that you use, such as spring or something else, in some framework that it can do this automatically, and send data to the client browser. – OQJF Jan 09 '13 at 05:51
  • @vmb - what's the expected output? – AlikElzin-kilaka Feb 25 '14 at 16:22
  • You can use GSON like this >> http://stackoverflow.com/a/15332888/3920648 it work for me – Telember Jan 18 '15 at 15:16

8 Answers8

150

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

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
code_fish
  • 3,381
  • 5
  • 47
  • 90
14

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.

Rahul
  • 15,979
  • 4
  • 42
  • 63
7

jackson provides very helpful and lightweight API to convert Object to JSON and vise versa. 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. you can refer to the links like: 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>
Kushagra Misra
  • 461
  • 1
  • 7
  • 15
4

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.

NamingException
  • 2,388
  • 1
  • 19
  • 41
3

Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.

Dave G
  • 9,639
  • 36
  • 41
3

download java-json.jar from Java2s then use the JSONArray constructor

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

For simplicity and well structured sake, use 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

zawhtut
  • 8,335
  • 5
  • 52
  • 76
-1

Use GSONBuilder with setPrettyPrinting and disableHtml for nice output.

String json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().
                            create().toJson(outputList  );
                    fileOut.println(json);
Ammad
  • 4,031
  • 12
  • 39
  • 62