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<Integer, Map<String, String>> jsonmaps = new HashMap<Integer, Map<String, String>>(); int i=0; for (Object j : jsons) { Map<String, String> map = new HashMap<String, String>(); JSONObject o = (JSONObject) j; map = mapper.readValue(j.toString(), new TypeReference<Map<String, String>>() { }); 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(); } }