CMPS 121
Json (in Java)
Luca de Alfaro
Some material from the Google Gson library documentation.
JSON: JavaScript Object Notation
A simple, compact, readable way of sending data as strings. Not a binary format.
Rough comparison:
The way I think of it:
JSON: a simple, readable way to serialize (somewhat simple) data structures to strings.
JSON Examples (in Python)
JSON in Java
There are several libraries; my favorite is google-gson (aka Gson).
Serialization of simple values:
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]
JSON in Java using Gson
Deserialization of simple values:
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class);
Serializing some data
class MyMsg {
MyMsg() {};
public int id;
public String name;
public int[] values;
}
(Serialization)
MyMsg obj = new MyMsg();
obj.id = 3;
obj.name = "Example";
obj.values = {1, 2, 3, 4}
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"id":3,"name":"Example", "values": [1, 2, 3, 4]}
Deserializing it
class MyMsg {
MyMsg() {};
public int id;
public String name;
public int[] values;
}
(Deserialization)
Gson gson = new Gson();
try {
MyMsg obj = gson.fromJson(json, MyMsg.class);
} catch (JsonSyntaxException ex) {
// Do something.
}
Missing fields in JSON are translated to default values (null, 0, ...).
Arrays of objects
class MyMsg {
MyMsg() {};
public int id;
public String name;
public int[] values;
}
(Serialization)
MyMsgList[] msgList = new MyMsg[10];
...
Gson gson = new Gson();
String json = gson.toJson(msgList);
(Deserialization)
MyMsgList[] msgList = gson.fromJson(json, MyMsg[].class);