My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
EncodingExamples  
Examples of JSON encoding
Updated Dec 19, 2012 by fangyid...@gmail.com

Example 1-1 - Encode a JSON object

  //import org.json.simple.JSONObject;
  
  JSONObject obj=new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  System.out.print(obj);
Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
JSONObject is subclass of java.util.HashMap. No ordering is provided. If you need strict ordering of elements use JSONValue.toJSONString( map ) method with ordered map implementation such as java.util.LinkedHashMap (see example 1-3).
Please refer Mapping Between JSON and Java Entities for more information.

Example 1-2 - Encode a JSON object - Streaming

  //import org.json.simple.JSONObject;
  
  JSONObject obj=new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  StringWriter out = new StringWriter();
  obj.writeJSONString(out);
  String jsonText = out.toString();
  System.out.print(jsonText);
Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
JSONObject is subclass of java.util.HashMap. No ordering is provided. If you need strict ordering of elements use JSONValue.toJSONString( map ) method with ordered map implementation such as java.util.LinkedHashMap (see example 1-3). Please refer Mapping Between JSON and Java Entities for more information.

Example 1-3 - Encode a JSON object - Using Map

  //import java.util.LinkedHashMap;
  //import java.util.Map;
  //import org.json.simple.JSONValue;
  
  Map obj=new LinkedHashMap();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  String jsonText = JSONValue.toJSONString(obj);
  System.out.print(jsonText);
Result: {"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}
Now the order of the object entries is preserved, which is different from example 1-1. Please refer Mapping Between JSON and Java Entities for more information.

Example 1-4 - Encode a JSON object - Using Map and streaming

  //import java.util.LinkedHashMap;
  //import java.util.Map;
  //import org.json.simple.JSONValue;
  
   Map obj=new LinkedHashMap();
   obj.put("name","foo");
   obj.put("num",new Integer(100));
   obj.put("balance",new Double(1000.21));
   obj.put("is_vip",new Boolean(true));
   obj.put("nickname",null);
   StringWriter out = new StringWriter();
   JSONValue.writeJSONString(obj, out);
   String jsonText = out.toString();
   System.out.print(jsonText);
Result: {"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}
Please refer Mapping Between JSON and Java Entities for more information.

Example 2-1 - Encode a JSON array

  //import org.json.simple.JSONArray;
  
  JSONArray list = new JSONArray();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  System.out.print(list);
Result: ["foo",100,1000.21,true,null]

Example 2-2 - Encode a JSON array - Streaming

  //import org.json.simple.JSONArray;
  
  JSONArray list = new JSONArray();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  StringWriter out = new StringWriter();
  list.writeJSONString(out);
  String jsonText = out.toString();
  System.out.print(jsonText);
Result: ["foo",100,1000.21,true,null]
Please refer Mapping Between JSON and Java Entities for more information.

Example 2-3 - Encode a JSON array - Using List

  //import org.json.simple.JSONValue;
  
  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  String jsonText = JSONValue.toJSONString(list);
  System.out.print(jsonText);
Result: ["foo",100,1000.21,true,null]
Please refer Mapping Between JSON and Java Entities for more information.

Example 2-4 - Encode a JSON array - Using List and streaming

  //import org.json.simple.JSONValue;

  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  StringWriter out = new StringWriter();
  JSONValue.writeJSONString(list, out);
  String jsonText = out.toString();
  System.out.print(jsonText);
Result: ["foo",100,1000.21,true,null]
Please refer Mapping Between JSON and Java Entities for more information.

Example 3 - Merge two JSON objects

  //import org.json.simple.JSONObject;
  
  JSONObject obj1 = new JSONObject();
  obj1.put("name","foo");
  obj1.put("num",new Integer(100));
  obj1.put("balance",new Double(1000.21));
  		
  JSONObject obj2 = new JSONObject();
  obj2.put("is_vip",new Boolean(true));
  obj2.put("nickname",null);
  obj2.putAll(obj1);
  System.out.print(obj2);
Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}, the same as the one of Example 1.

Example 4 - Merge two JSON arrays

  JSONArray list1 = new JSONArray();
  list1.add("foo");
  list1.add(new Integer(100));
  list1.add(new Double(1000.21));
  
  JSONArray list2 = new JSONArray();
  list2.add(new Boolean(true));
  list2.add(null);
  list2.addAll(list1);
  System.out.print(list2);
Result: [true,null,"foo",100,1000.21], the order of which is different from the one of Example 2.

Example 5-1 - Combination of JSON primitives, JSON object and JSON arrays

  JSONArray list1 = new JSONArray();
  list1.add("foo");
  list1.add(new Integer(100));
  list1.add(new Double(1000.21));
  
  JSONArray list2 = new JSONArray();
  list2.add(new Boolean(true));
  list2.add(null);
		
  JSONObject obj = new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
    
  obj.put("list1", list1);
  obj.put("list2", list2);
		
  System.out.println(obj);
Result: {"balance":1000.21,"list2":[true,null],"num":100,"list1":["foo",100,1000.21],"nickname":null,"is_vip":true,"name":"foo"}

Example 5-2 - Combination of JSON primitives, Map and List

  Map m1 = new LinkedHashMap();
  Map m2 = new HashMap();
  List  l1 = new LinkedList();

  m1.put("k11","v11");
  m1.put("k12","v12");
  m1.put("k13", "v13");
  m2.put("k21","v21");
  m2.put("k22","v22");
  m2.put("k23","v23");
  l1.add(m1);
  l1.add(m2);

  String jsonString = JSONValue.toJSONString(l1);
		
  System.out.println(jsonString);
Result: [{"k11":"v11","k12":"v12","k13":"v13"},{"k22":"v22","k21":"v21","k23":"v23"}]

Example 5-3 - Combination of JSON primitives, JSONObject, Map and List, and streaming

  StringWriter out = new StringWriter();
        
  JSONObject obj = new JSONObject();
  LinkedHashMap m1 = new LinkedHashMap();
  LinkedList l1 = new LinkedList();
  obj.put("k1", "v1");
  obj.put("k2", m1);
  obj.put("k3", l1);
  m1.put("mk1", "mv1");
  l1.add("lv1");
  l1.add("lv2");
  m1.put("mk2", l1);
        
  obj.writeJSONString(out);
  System.out.println("jsonString:");
  System.out.println(out.toString());
  String jsonString = obj.toJSONString();
  System.out.println(jsonString);
Result:
  jsonString:
  {"k3":["lv1","lv2"],"k1":"v1","k2":{"mk1":"mv1","mk2":["lv1","lv2"]}}
  {"k3":["lv1","lv2"],"k1":"v1","k2":{"mk1":"mv1","mk2":["lv1","lv2"]}}

Example 6-1 - Customize JSON outputs

/*class User implements JSONAware{
	private int id;
	private String name;
	private String password;
	
	public User(int id, String name, String password){
		this.id = id;
		this.name = name;
		this.password = password;
	}
	
	public String toJSONString(){
		StringBuffer sb = new StringBuffer();
		
		sb.append("{");
		
		sb.append(JSONObject.escape("userName"));
		sb.append(":");
		sb.append("\"" + JSONObject.escape(name) + "\"");
		
		sb.append(",");
		
		sb.append(JSONObject.escape("ID"));
		sb.append(":");
		sb.append(id);
		
		sb.append("}");
		
		return sb.toString();
	}
}*/

  JSONArray users = new JSONArray();
  users.add(new User(123,"foo1", "secret1"));
  users.add(new User(124,"foo2", "secret2"));
  users.add(new User(125,"\"foo2\"", "secret2"));
  System.out.println(users);
Result: [{userName:"foo1",ID:123},{userName:"foo2",ID:124},{userName:"\"foo2\"",ID:125}]
User.toJSONString() seems to be a bit complicated. The purpose is to demonstrate the usage of JSONObject.escape(). It can be simpler:
  public String toJSONString(){
    JSONObject obj = new JSONObject();
    obj.put("userName", name);
    obj.put("ID", new Integer(id));
    return obj.toString();
  }
Please refer Mapping Between JSON and Java Entities for more information. (Note: If you are using version 1.0.2 or earlier, you need to override Object.toString() of your bean to get customized output.)

Example 6-2 - Customize JSON outputs - Streaming

/*class User implements JSONStreamAware{
	private int id;
	private String name;
	private String password;
	
	public User(int id, String name, String password){
		this.id = id;
		this.name = name;
		this.password = password;
	}
	
       public void writeJSONString (Writer out) throws IOException{
                LinkedHashMap obj = new LinkedHashMap();
                obj.put("userName", name);
                obj.put("ID", new Integer(id));
                JSONValue.writeJSONString(obj, out);
       }
}*/

  JSONArray users = new JSONArray();
  users.add(new User(123,"foo1", "secret1"));
  users.add(new User(124,"foo2", "secret2"));
  users.add(new User(125,"\"foo2\"", "secret2"));
  StringWriter out = new StringWriter();
  users.writeJSONString(out);
  System.out.println(out.toString());
Result: [{"userName":"foo1","ID":123},{"userName":"foo2","ID":124},{"userName":"\"foo2\"","ID":125}]
Please note that you don't have to implement JSONStreamAware to support streaming output of your bean, you can only implement JSONAware instead of JSONStreamAware. In the latter case, JSONAware.toString() is called and the result is written to the output stream. You can implement JSONStreamAware for better performance. If a class implements both JSONStreamAware and JSONAware, JSONStreamAware is given precedence while streaming. Please refer Mapping Between JSON and Java Entities for more information.
Comment by anujgupt...@gmail.com, Mar 20, 2009

i have a very complex data structure with me its LinkedHashmap? of LinkedHashmap? of LinkedHashmap? of ArrayList?. when i try to use JSONValue.toJSONString it does not work properly. can you suggest what should i do?

my main aim is to maintain the order of the objects in my collection i was using net.sf.json.JSONObject till now. but its messing up with the order in my linkedHashmaps.

can you suggest what should i do?

Comment by project member fangyid...@gmail.com, Mar 21, 2009

JSONValue.toJSONString() should preserve the order of entries determined by the LinkedHashMap?. Could you provide sample code on the discussion group? Thanks.

Comment by java.ko...@gmail.com, Nov 16, 2009

This is great, thank you :)

Comment by sophiaco...@gmail.com, Mar 19, 2010

Hi,

I need that the output must not be escaped. Unfortunately, I didn't see an easy way to do that (unable to derive JSONObject because there are static methods. So I'll write a simple method like this called when the process is done:

protected String removeEscapeChar(final String aString) {
StringBuffer? stringbuffer = new StringBuffer?(aString.length());
for(int i = 0; i < aString.length(); i++) {
char c = aString.charAt(i); if (c != 92)
stringbuffer.append(c);
}
return stringbuffer.toString();
}

Maybe, could you create a new constructor that prevent to escape the output...

Comment by Niels...@gmail.com, Jun 21, 2010

But not escaping output is really dangerous! If you by accident encode a string containing quotes, newlines or similar, it will break. If at all possible, challenge this requirement.

Anyway, you could write your code simpler and probably more efficient as protected String removeEscapeChar(final String aString) {

return aString.replaceAll("\\\\", "");
} or use StringUtils? form apache commons lang: StringUtils?.remove(aString, '\\');

At the very least, you should change if (c != 92) to if (c != '\\') - using the ascii code is just obscure.

Comment by cristi.c...@gmail.com, Jan 10, 2011

how to encode json coming from a link. ex: http://google.com/json_folder

Comment by kchidam...@gmail.com, Mar 18, 2011

Handling multiple Object Convert multiple Object to Key pair String

//sample/Student.java

package sample; public class Student {

private int rollno;
private String name; private int marks;
/
  • @return the rollno
public int getRollno() {
return rollno;
}
/
  • @param rollno the rollno to set
public void setRollno(int rollno) {
this.rollno = rollno;
}
/
  • @return the name
public String getName() {
return name;
}
/
  • @param name the name to set
public void setName(String name) {
this.name = name;
}
/
  • @return the marks
public int getMarks() {
return marks;
}
/
  • @param marks the marks to set
public void setMarks(int marks) {
this.marks = marks;
}

}

Comment by kchidam...@gmail.com, Mar 18, 2011

//Example.jsp

<%@page import="org.json.simple.JSONValue"%> <%@page import="java.util.Iterator"%> <%@page import="java.util.ArrayList?"%> <%@page import="sample."%> <%@page import="org.json.simple.JSONObject"%>

<%

ArrayList? stud=new ArrayList?();
Student firstObj=new Student();
firstObj.setRollno(1);
firstObj.setName("Chidam");
firstObj.setMarks(60);
Student secondObj=new Student();
secondObj.setRollno(2);
secondObj.setName("Sundar");
secondObj.setMarks(90);
stud.add(firstObj);
stud.add(secondObj);
Iterator it=stud.iterator();
JSONObject firstJSONObject;
JSONObject secondJSONObject=new JSONObject();

Student sk=null;
while(it.hasNext())
{
firstJSONObject=new JSONObject();

sk=(Student)it.next();
firstJSONObject.put("rollno",sk.getRollno());
firstJSONObject.put("name",sk.getName());
firstJSONObject.put("marks",sk.getMarks());
secondJSONObject.put(sk.getRollno(), firstJSONObject);
}
String jsonText = JSONValue.toJSONString(secondJSONObject);
out.println("{\" JString\" :"+jsonText+"}");
out.flush();
%>

output : {" JString" :{"1":{"rollno":1,"marks":60,"name":"Chidam"},"2":{"rollno":2,"marks":90,"name":"Sundar"}}}

Comment by baran.so...@gmail.com, Apr 12, 2011

thanks for a really good package!

Comment by hari.ran...@gmail.com, Aug 1, 2011

I have a structure like this ,

[Note{"id:""1","title:""Abcd","tasks:""[{"id:""1","tascdesc:""sfsfsf"}, {"id:""2","tascdesc:""sfsfsf"}]" }] Arraylist of Note object each Note has Arraylist of task object

I am unable to encode using Json Simple. Any help will be appreciated .Thank you!

Comment by paul.reb...@gmail.com, Oct 12, 2011

(assumed intended object structure)

         ArrayList Notes = new ArrayList();
         LinkedHashMap note = new LinkedHashMap();
         LinkedHashMap nobj = new LinkedHashMap();
         nobj.put("id", "1");
         nobj.put("title", "Abcd");
         ArrayList tlist = new ArrayList();
         LinkedHashMap tobj1 = new LinkedHashMap();
         tobj1.put("id", "1");
         tobj1.put("tascdesc", "desc for tobj1");
         LinkedHashMap tobj2 = new LinkedHashMap();
         tobj2.put("id", "2");
         tobj2.put("tascdesc", "desc fot tobj2");
         tlist.add(tobj1);
         tlist.add(tobj2);
         nobj.put("tasks", tlist);
         note.put("Note", nobj);
         Notes.add(note);
         s = JSONValue.toJSONString(Notes); 
         System.out.println(s);

output: [{"Note":{"id":"1","title":"Abcd","tasks":[{"id":"1","tascdesc":"desc for tobj1"},{"id":"2","tascdesc":"desc fot tobj2"}]}}]

Comment by trie...@gmail.com, Nov 14, 2011

good for me.

Thanks all!

Comment by karim.va...@gmail.com, Feb 15, 2012

Can someone please tell me what the difference is between json.simple and org.json?

Comment by westsinc...@gmail.com, Feb 21, 2012

as it named this is simple and wrappered more Functions for json。other way org.json is the standar.such as JDK OF SUN. and simple josn as the JDK OF IBM.

Comment by ajit.gu...@finicity.com, Mar 19, 2012

How to post json request with the help of htmlunit

Comment by p.sagars...@gmail.com, Aug 14, 2012

How to encode json string in struts2 jquery grid? what is jsonmap? please tell me about those two

Comment by imakshat...@gmail.com, Mar 31, 2013

Excellent Tutorial. Very usefull for me.

Comment by paternos...@gmail.com, Apr 22, 2013

Thanks for the useful library!

Can I "prettify" the output? I would like to preserve a decent formatting with large object : i.e. no single line please ;

Comment by florentv...@gmail.com, May 3, 2013

It does not seem possible to prettify with json-simple. I am using an external library to do such

=> https://code.google.com/p/google-gson/

Gson gson = new GsonBuilder?().setPrettyPrinting().create(); String jsonOutput = gson.toJson(someObject);

Comment by boulver...@gmail.com, Jul 1, 2013

that is cool and sound something different

Comment by reyicla...@gmail.com, Aug 6, 2013

Super bueno la explicacion

Comment by Dave.Len...@gmail.com, Oct 3, 2013

What's the best practice for converting a Map where the keys aren't a primitive type but do implement JSONAware?

ex: HashMap?<CustomClass1?, CustomClass2?> myCustomMap;

Right now, JSONObject class .toString() on the key, and .toJSONString() on the entry.

Should I instead, for conversions sake, convert the custom map into an array of keys (stored as a JSONObject with the array index as the key and the original key as the entry) and store the entries using the same set of array indices? Obviously tedious, and hard to manage changes, but I mainly need a way to store and retrieve.

Thoughts?

Comment by mobi.rap...@gmail.com, Oct 8, 2013

Is there a way to preserve trailing zeroes in floats?

Comment by radjobse...@gmail.com, Oct 21, 2013

can anyone help me for attaching more than one file to JSON object in java dynamically? Is there any way for this?

Comment by pereira....@gmail.com, Dec 10, 2013

Awsm tutorial..great work..Thnks:)

Comment by sathishm...@gmail.com, Dec 11, 2013

Hello Sir,

My input is json data. it's look's like [{"shortName":"av","longName":"average","Color":"black","fromValue":"45","toValue":"59"},{"shortName":"g","longName":"good","Color":"red","fromValue":"35","toValue":"68"}]

I need to store this json data in to one list of object (PerformanceLevel??.java) class. How can i do? can you please give me some idea on this.

Thanks, Sathish.H

Comment by chetan.a...@gmail.com, Feb 3, 2014

Hi Satish You can also use Jackson library

You need to a POJO as Grade.java

// Grade.java private String shortName; private String longName; private String color; private int fromValue; private int toValue; // setter and getter omitted

and parse using Jackson in another java code List<Grade> grades = null; grades = new ObjectMapper?().readValue(

new InputStreamReader?(ReadGradeJson?.class.getClassLoader().
getResourceAsStream("grades.json")),new TypeReference?<List<Grade>>() {});

Comment by bhaskar....@gmail.com, Feb 6, 2014

Thanks for sharing this information. I just started learning things, just one question....I want to create JSON file like below (in java).... Could you please suggest ( just high level ) how to create this... {

"CN" : "" , "Jd" : "" , "Fdate" : "" , "Location" : "" , "Type" : "" ,
"PInfo" : [
{ "Name" : "" , "Relationship" : "" , "Sex" : "" }, { "Name" : "" , "Relationship" : "" , "Sex" : "" }, .....so on
]
"Docs" : [
{ "Date" : "", "Description" : "" , "DoK" : "" , "FPar" : "" , "NOTE" : "" }, { "Date" : "", "Description" : "" , "Dok" : "" , "FPar" : "" , "NOTE" : "" }, { "Date" : "", "Description" : "" , "Dok" : "" , "FPar" : "" , "NOTE" : "" } ..... so on
]

"Calendar" : [

{ "CalendarDate?": "" , "CalendarTime?": "" , "Evt": }, { "CalendarDate?": "" , "CalendarTime?": "" , "Evt": }, { "CalendarDate?": "" , "CalendarTime?": "" , "Evt": }
...... so on...
]

}

Comment by alagusls...@gmail.com, Feb 13, 2014

Great coding. I am learn for many information about json files. This tutorial is really nice. Thanks for sharing this information. http://www.dreamdestinations.in/

Comment by JCFinne...@gmail.com, Feb 18, 2014

Thank you so much, this is great! Have been looking some time for this!

Comment by abdulmal...@gmail.com, Feb 24, 2014

I am having a complex format.Pls give me an idea about how to generate java object. JSON to JAVA viceversa. JSON CODE: [{"LengthMax?":0,"LengthMin?":0,"ByteLength?":"1","CIFName":"XYZ","DataType?":"integer","AreSubTypes?":true,"Type":"78","SubTypeArray?":[{"LengthMax?":2,"LengthMin?":2,"Value":1,"ByteLength?":"1","CIFName":"XYZ","DataType?":"integer","AreSubTypes?":false,"Type":"1","CIFDescription":"description","SupportedVersion?":"16.7","ParentTypeList?":[-1,78,1]},{"LengthMax?":2,"LengthMin?":2,"Value":1,"ByteLength?":"1","CIFName":"XYZ","DataType?":"integer","AreSubTypes?":false,"Type":"2","CIFDescription":"description","SupportedVersion?":"16.7","ParentTypeList?":[-1,78,2]}]"CIFDescription":"description","SupportedVersion?":"1.1"},{"LengthMax?":0,"LengthMin?":0,"ByteLength?":"1","CIFName":"XYZ","DataType?":"integer","AreSubTypes?":true,"Type":"78","SubTypeArray?":[{"LengthMax?":2,"LengthMin?":2,"Value":1,"ByteLength?":"1","CIFName":"XYZ","DataType?":"integer","AreSubTypes?":false,"Type":"1","CIFDescription":"description","SupportedVersion?":"16.7","ParentTypeList?":[-1,78,1]},{"LengthMax?":2,"LengthMin?":2,"Value":1,"ByteLength?":"1","CIFName":"XYZ","DataType?":"integer","AreSubTypes?":false,"Type":"2","CIFDescription":"description","SupportedVersion?":"16.7","ParentTypeList?":[-1,78,2]}]"CIFDescription":"description","SupportedVersion?":"1.1"}]

Comment by duyetpt1...@gmail.com, May 15, 2014

thanks you !

Comment by josephyk...@gmail.com, Jul 22, 2014

If I've a jsonstring, what is the easiest way to convert it back to ArrayList?<LinkedHashMap?<String, String> > objects?

Comment by gorumlab...@gmail.com, Aug 19, 2014

I want to do this using JsonObject? {

{column1:value1, column2:value2}, {column1:value3, column2:value4}, .... {column1:valueN, column2:valueN},
}


Sign in to add a comment
Powered by Google Project Hosting