How to read the JSON object from file and parse in java springboot
Use the below code to read file from your drive and than covert into JSON object using GSON Apis.
Use the below repositay from GSON.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Find my JSON file data as below .
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class JsonParserTest { public static void main(String[] args) throws IOException { String data = new String(Files.readAllBytes(Paths.get("C:/json.txt"))); JsonElement jsonElement = JsonParser.parseString(data); JsonObject json = jsonElement.getAsJsonObject(); System.out.println(json.get("userId")); System.out.println(json.get("id")); System.out.println(json.get("title")); System.out.println(json.get("completed")); } }
No comments: