1 of 8

CMPS 121

Json (in Java)

Luca de Alfaro

Some material from the Google Gson library documentation.

2 of 8

JSON: JavaScript Object Notation

A simple, compact, readable way of sending data as strings. Not a binary format.

Rough comparison:

  • XML: Good for structured content (documents, things with a tree structure, things with a hierarchical organization) and streams (things that do not end).
  • JSON: Good for passing values to and from web services, and generally for encoding non-hierarchical structures to strings.

The way I think of it:

JSON: a simple, readable way to serialize (somewhat simple) data structures to strings.

3 of 8

JSON Examples (in Python)

4 of 8

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]

5 of 8

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

6 of 8

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]}

7 of 8

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, ...).

8 of 8

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