How to parse JSON in Java

[CG]BOUGA
1,731 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Using Gson

1
10
11
12
13
14
15
16
17
18
19
20
21
// {...}
String json = "{\"name\": \"Bob\", \"id\": \"123\"}";
// Method 1: parsing into a JSON element
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString());
// Method 2: parsing into a Java Object
User user = new Gson().fromJson(json, User.class);
System.out.println(user.id);
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content