Parse a JSON file in Java I am using Java to parse a JSON file into a hash map so that i can search by typing a date and then get the cost, tax and profit for that date.

So that if i write:

2001-09-18 13:11:01


I get:

7.14, 1.81 and 31.10


Here is part of the JSON file:

{  
  "stat":[  
    {  
      "date":" 2001-09-18 13:11:01 ",
      "cost":" 7.14 ",
      "tax":" 1.81 ",
      "profit":" 31.10 "
    },
    {  
      "date":" 2001-09-18 14:15:02 ",
      "cost":" 7.80 ",
      "tax":" 0.99 ",
      "profit":" 30.20 "
    }
  ]
}


And my code using Jackson:

public static void main(String[] args) throws JsonGenerationException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JSONParser parser = new JSONParser();
            JSONObject jsonobj = (JSONObject) parser.parse(new FileReader("test.json"));    
            JSONArray jsons = (JSONArray) jsonobj.get("stat");
            Map&lt;Integer, Map&lt;String, String&gt;&gt; jsonmaps = new HashMap&lt;Integer, Map&lt;String, String&gt;&gt;();
            int i=0;
            for (Object j : jsons) {
                Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
                JSONObject o = (JSONObject) j;
                map = mapper.readValue(j.toString(), new TypeReference&lt;Map&lt;String, String&gt;&gt;() {
                });
                jsonmaps.put(i, map);
                i++;
            }
            System.out.println(jsonmaps.get(0).get("date"));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
The initial value of a map variable is not used, you can avoid this assignment and inline the variable. o is not used too.

If indexes in a map is consequent then it is better to use a List instead of Map. So the part of the code can be rewritten following way:

List&lt;Map&lt;String, String&gt;&gt; jsonmaps = new ArrayList&lt;&gt;();
for (Object j : jsons) {
    jsonmaps.add(mapper.readValue(j.toString(),
        new TypeReference&lt;Map&lt;String, String&gt;&gt;() {}));
}