In
this post, I am going to explain, how can you parse a json file using gson
library.
Previous
Next
Home
For
example, consider below json file.
testApp.json
{ "login" : { "userName" : "krishna", "password" : "krishna" }, "homePage" : { "welcomeMessage" : "Hello Krishna", "buttonId" : "saveYourChanges" } }
Below
step-by-step procedure explains, how to parse login element from testApp.json
file.
Step 1: Create the
instance of JsonParser.
JsonParser
jsonParser = new JsonParser();
Step 2: Read the json
data from given file.
String
jsonData = new String(Files.readAllBytes(Paths.get(jsonFilePath)));
Step 3: Get the root
element by parsing the data.
JsonObject
rootElement = (JsonObject)jsonParser.parse(jsonData);
Step 4: Now you can
parse the element by using element name.
For
example, below statement retrieves the json element with name 'login'.
JsonObject
loginElement =
(JsonObject)jsonParser.parse(rootElement.get("login").toString());
Find
the below working application.
Test.java
package com.sample.files; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; import java.util.Set; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class Test { private static String jsonFilePath = "C:\\Users\\krishna\\testApp.json"; public static void main(String args[]) throws Exception { JsonParser jsonParser = new JsonParser(); String jsonData = new String(Files.readAllBytes(Paths.get(jsonFilePath))); JsonObject rootElement = (JsonObject)jsonParser.parse(jsonData); JsonObject loginElement = (JsonObject)jsonParser.parse(rootElement.get("login").toString()); Set<Map.Entry<String, JsonElement>> entrySet = loginElement.entrySet(); for(Map.Entry<String, JsonElement> entry : entrySet){ String key = entry.getKey(); String value = entry.getValue().getAsString(); System.out.println("key : " + key + ", value : " + value); } } }
Output
key : userName, value : krishna key : password, value : krishna
No comments:
Post a Comment