Json object:
You easily write your object in json format with java . Json format is used because it becomes easy to exchange information in this form. It is easy to understand and easy to write.
Lets see an example,
If you are using maven add the following dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
or you can download the json-simple.jar file.
First, lets do it in simple way:
CreateJson.java
import org.json.simple.JSONObject;
public class CreateJson {
@SuppressWarnings("unchecked")
public static void main(String args[]){
JSONObject json=new JSONObject();
json.put("name","Chris");
json.put("id",new Integer(01));
json.put("email","chris@yahoo.com");
System.out.print(json);
}
}
Output:
{"name":"Chris","id":1,"email":"chris@yahoo.com"}
We can create Json object by using Map also, lets see how,
CreateJson.java
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONValue;
public class CreateJson{
public static void main(String args[]){
Map<String,Object> map=new HashMap<String,Object>();
map.put("name","Mark");
map.put("id",new Integer(04));
map.put("address","4 th Street, UK");
String json = JSONValue.toJSONString(map);// Converting map to Json
System.out.println(json);
}
}
Output:
{"address":"4 th Street, UK","name":"Mark","id":4}
This way, Map can be directly used to give output in json format.
0 Comment(s)