Expand my Community achievements bar.

SOLVED

JSON Parser

Avatar

Level 2

Is there any way to Parse the JSON and get the desired result out of JSON in java.

1 Accepted Solution

Avatar

Correct answer by
Level 7

Hi,

The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. Before you can use the GSON JsonParser you must create a JsonParser instance. Here is an example of creating a JsonParser instance:

JsonParser jsonParser = new JsonParser();

Parsing JSON Into a Tree Structure:

Once you have created a JsonParser you 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 = "{ \"key1\":\"Hello\",\"key2\":{\"key3:\":\"World\"}}";

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.

The above JsonElement (jsonTree) can be converted into JsonObject as -

JsonObject jsonObj = jsonTree.getAsJsonObject(); //converting JsonElement  into JsonObject

jsonObj .get("key1"); //gets key1 from json

In this way, GSON API can be used for parsing the JSON and getting desired result out of it.

NOTE: GSON is the alternative of deprecated JSON API in AEM 6.3.

For more information on this, please refer:

Gson (Gson 2.6.2 API)

Gson 2.6.2 API

Hope this helps!

Regards,

TechAspect Solutions

View solution in original post

4 Replies

Avatar

Correct answer by
Level 7

Hi,

The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. Before you can use the GSON JsonParser you must create a JsonParser instance. Here is an example of creating a JsonParser instance:

JsonParser jsonParser = new JsonParser();

Parsing JSON Into a Tree Structure:

Once you have created a JsonParser you 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 = "{ \"key1\":\"Hello\",\"key2\":{\"key3:\":\"World\"}}";

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.

The above JsonElement (jsonTree) can be converted into JsonObject as -

JsonObject jsonObj = jsonTree.getAsJsonObject(); //converting JsonElement  into JsonObject

jsonObj .get("key1"); //gets key1 from json

In this way, GSON API can be used for parsing the JSON and getting desired result out of it.

NOTE: GSON is the alternative of deprecated JSON API in AEM 6.3.

For more information on this, please refer:

Gson (Gson 2.6.2 API)

Gson 2.6.2 API

Hope this helps!

Regards,

TechAspect Solutions