Converted a Json String to a Java object using objectMapper . Now from Json array I can not get the value for Cod or dtBeg . deserialize.getAlgorithms prints an array.

here is json

{ "status": 1, "message": "ok", "sheduleCod": "NOST_A_Persons_m_noaccum", "algorithms": [{ "cod": "No_st_alg_1", "kcp": "U6000427", "dtBeg": "2017-11-01 00:00:00", "dtEnd": "2017-12-01 00:00:00" }, { "cod": "No_st_alg_2", "kcp": "U6000427", "dtBeg": "2017-11-01 00:00:00", "dtEnd": "2017-12-01 00:00:00" }, { "cod": "No_st_alg_3", "kcp": "U6000427", "dtBeg": "2017-11-01 00:00:00", "dtEnd": "2017-12-01 00:00:00" }] 

}

Main.Class

 JsonDeserialize deserialize = objectMapper.readValue(jsonString, JsonDeserialize.class); System.out.println(deserialize.getAlgorithms) 
  • System.out.println(deserialize.getAlgorithms[0].getCod) - Igor
  • bug in getAlgortihms. @ Igor - Marks
  • algorithms you have an array. You need to sort it out or pull it on the index. - Sergey
  • @ Sergey is true, but I don’t know how to over all Cod values ​​in the array - Marks
  • I can not check for the computer right now. But what if for (int i = 0; i <deserialize.getAlgorithms.lenght; i ++) {// do something ...} - Sergey

1 answer 1

Without serializers (using org-json):

 String jsonString = "{}"; try { JSONObject response = new JSONObject(jsonString); JSONArray algorithms = response.getJSONArray("algorithms"); for (int i = 0; i < algorithms.length(); i++) { JSONObject j = algorithms.getJSONObject(i); String cod = j.getString("cod"); } } catch (JSONException e) { e.printStackTrace(); } 
  • it works! thank. but the reason is that I use serialization, because I will continue to compare these values ​​with other values, in this case it turns out inconveniently. - Marks
  • if you always have the same set of keys, ie the json structure, then you can create a clear class and it turns out that serialization is only more understandable. - Sergey
  • I have a clear class with getters and setters for the whole json object and a separate class for algorithms . Serialization is understandable, only here it is impossible to pull the values ​​from there. I need these values ​​to compare them with the database. Here is such a problem - Marks
  • then I did not quite understand how you compare and what exactly - Sergey
  • in the algorithms array, I take cod (there are three of them in the array) and compare them with String cod = "No_st_alg_2" and it is his dtBeg that I take to load in the database - Marks