Knowledge Walls
John Peter
Pune, Maharashtra, India
How to Convert Java Object to JSON String in Core Java with Example
2764 Views
Hints 
Gson is a google external library. Gson handles JSON string to Java Object conversion uses toJson() method to creates JSON string by Java Objects.

Example
new Gson().toJson(<Java Object>);
JavaObjectToJSONObject
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class JavaObjectToJSONObject {
    public static void main(String args[]) throws Exception {
        List<String> nameList = new ArrayList<String>();
            nameList.add("Raja");
            nameList.add("Kumar");
            nameList.add("Vijay");
            nameList.add("Sam");
            nameList.add("Guru");
        
        String jsonString = new Gson().toJson(nameList);
        System.out.println(jsonString);
    }
}
Output 
["Raja","Kumar","Vijay","Sam","Guru"]
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details