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();
        }
    }
}

1 Answer 1

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));
        }
Sign up to request clarification or add additional context in comments.

4 Comments

Where do I get the .jar file able to import getInt and getDouble?
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.
I have json-simple.jar. Everything else works, but not getting int or double.
write jsonArray.getJSONObject(i).getInt("key")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.