GSON - JsonParser

It a parser to parse Json into a parse tree of JsonElements, The GSON's JsonParser class can parse a JSON string or stream into a tree structure of Java objects.

Creating a JsonParser

JsonParser jsonParser = new JsonParser();

Parsing JSON Into a Tree Structure

Once we created a JsonParser we can parse JSON into a tree structure with it. Here is an example of parsing a JSON string into a tree structure of GSON objects with the JsonParser:

JsonParser parser = new JsonParser();
String json = "{ \"name\":\"Alex\",\"age\":29}";
JsonElement jsonTree = parser.parse(json);

The parsing of the JSON happens in the third line of code, by calling parse() on the JsonParser, passing as parameter a reference to the JSON string (or stream) to parse.

Iterating the JSON Tree Structure

The parsed JSON tree structure consists of objects from the GSON API. The root of a JSON tree structure is a JsonElement object. we can find out what type of JSON element it represents using one of the type checking methods:


Abocve JSON string parsed as a JSON object. Thus, we will expect the JsonElement to represent a JSON object. Check this snippet:

if(jsonTree.isJsonObject()) {
    JsonObject jsonObject = jsonTree.getAsJsonObject();

Once we have a JsonObject instance we can extract fields from it using it's get() method. Here is an example:

JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement name = jsonObject.get("name");
JsonElement age = jsonObject.get("age");

Complete Example of JsonParser

 * @author
package com.tutorialtous.gson;


public class JSonParserExample {
  public static void main(String args[]) {
    String jsonstring = "{\"name\":\"Alex\",\"age\":29}";
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(jsonstring);
    if (element.isJsonObject()) {
      JsonObject jsonobj = element.getAsJsonObject();
      if (jsonobj.get("name") != null) {
      if (jsonobj.get("age") != null) {

Copyright © 2018-2020 TutorialToUs. All rights reserved.