gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
javacode for read json file
- User
javacode for read json file
- Assistant
Here is a simple Java code to read JSON file using the Gson library:
import java.io.BufferedReader; import java.io.FileReader; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; public class ReadJsonFile { public static void main(String[] args) { // File path String filePath = "C:\\example\\example.json"; // Read the JSON file try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(br); // Gson object Gson gson = new Gson(); String jsonString = gson.toJson(json); System.out.println(jsonString); } catch (Exception e) { e.printStackTrace(); } } }Here, we are using the Gson library to read and parse the JSON file. We are reading the JSON file using FileReader and BufferedReader, and then parsing its contents using JsonParser. Finally, we are converting the JsonElement object to a JSON string using the Gson.toJson() method. This code prints the JSON string on the console.