Search code examples
javajsongsonjson-simple

Java parse JSON array from JSON file


I haven't been programming for a long time but I like it and trying to get back on track. So please excuse the nature of the problem/question here.

What I need is pretty simple in my opinion but i'm mostly struggling with using gson and json-simple to read my json file, one at a time, and be able to retrieve the values.

I have seen many approaches on here but as I said been a while and I have not done Java a lot in my career. So need some guidance/explanation on the best approach.

JSON:

[{ "car": "Toyota", "colour": "red", "qty": "1","date_manufactured":"12972632260006" }, { "car": "Hyundai", "colour": "red", "qty": "2","date_manufactured":"1360421626000" }, { "car": "Kia", "colour": "blue", "qty": "2", "date_manufactured":"1265727226000"}, ]

Any help to put me on the right track is appreciated!


Solution

    1. Create a POJO class to represent your JSON data:

      public class CarInfo {  
        String car;
        String colour;
        String qty;
        String date_manufactured; 
      }
      
    2. Use GSON to parse JSON String Array

      String carInfoJson = "[{ \"car\": \"Toyota\", \"colour\": \"red\",\"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\":\"Hyundai\", \"colour\":\"red\",\"qty\":\"2\",\"date_manufactured\":\"1360421626000\" }]";
      Gson gson = new Gson();  
      CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);  
      
    3. Use GSON to parse JSON String Array from a file

      String carInfoJson= new String(Files.readAllBytes(Paths.get("filename.txt")));
      Gson gson = new Gson();  
      CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);
      
    4. Use GSON to parse JSON String Array from a file using BufferedReader

      BufferedReader reader = null;
      try {
        reader = new BufferedReader(new FileReader(file));
        Gson gson = new Gson(); 
        CarInfo[] carInfoArray = gson.fromJson(reader, CarInfo[].class);
      } catch (FileNotFoundException ex) {
        ...
      } finally {
        ...
      }
      
    5. Use GSON to parse JSON String Array from a file using JsonReader in stream mode

      try {
        InputStream stream = new FileInputStream("c:\\filename.txt");
        JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
        Gson gson = new Gson();
      
        // Read file in stream mode
        reader.beginArray();
        while (reader.hasNext()) {
          CarInfo carInfo = gson.fromJson(reader, CarInfo.class);
        }
        reader.endArray();
        reader.close();
      } catch (UnsupportedEncodingException ex) {
        ...
      } catch (IOException ex) {
        ...
      }