0

I have a JSON file

{
    "measurements": [
      {
        "time": "100416",
        "temp": "7.64",
      },
      {
        "time": "110416",
        "temp": " 7.76 ",
      },
      {
        "time": "120416",
        "temp": " 7.86 ",
      }
    ]
}

and I need to save the values as class objects( or Hashmap) with a key value of "time". Then while typing "time" for example: 120416 It will print the temp for that time. I'm using Netbeans.

This is where I'm so far. I can print an Array:

public class Weathers {
    private static final String filePath = "C:\\measurements.json";

    public static void main(String[] args) {
        try {

            FileReader reader = new FileReader(filePath);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

            JSONArray JArray = (JSONArray) jsonObject.get("measurements");
            for (int i =0;i <JArray.size();i++)
            {
            System.out.println(JArray.get(i));
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }
    }
}
Gaëtan Maisse
  • 12,208
  • 9
  • 44
  • 47
Sumsum
  • 1
  • 1

1 Answers1

1
 Map<Integer, Double> map = new HashMap<Integer, Double>();
        for (int i =0;i <JArray.size();i++)
        {
            map.put(JArray.get(i).getInt("time"),JArray.get(i).getDouble("temp"));
             System.out.println(JArray.get(i));
        }
coenni
  • 437
  • 4
  • 14
  • Where do I get the .jar file able to import getInt and getDouble? – Sumsum Mar 25 '17 at 11:21
  • which json library are you using? Almost all json libraries has this support. for example, I'm using org.json.simple.JSONObject, it has really simple usage about getting int, double from json object. – coenni Mar 25 '17 at 11:47
  • I have json-simple.jar. Everything else works, but not getting int or double. – Sumsum Mar 25 '17 at 12:02
  • write jsonArray.getJSONObject(i).getInt("key") – coenni Mar 25 '17 at 12:35