Guest User

Untitled

a guest
Jul 17th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import com.google.gson.*;
  5. import com.google.gson.JsonObject;
  6. import com.google.gson.JsonElement;
  7. import java.util.Iterator;
  8. import java.util.List;
  9. import java.util.ArrayList;
  10. import org.json.*;
  11. public class JsonParsing {
  12.  
  13.  
  14. static JsonParser parser = new JsonParser();
  15.  
  16.  
  17. public static void createHashMapFromJsonString(String json, int row_num)
  18.  
  19. {
  20.  
  21. JsonObject object = (JsonObject) parser.parse(json.toString());
  22. Set<Map.Entry<String, JsonElement>> set = ((JsonObject) object).entrySet();
  23. Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
  24. ArrayList<String> map = new ArrayList<String>();
  25. while (iterator.hasNext()) {
  26.  
  27. Map.Entry<String, JsonElement> entry = iterator.next();
  28. String key = entry.getKey();
  29. JsonElement value = entry.getValue();
  30.  
  31. if (null != value) {
  32. if (!value.isJsonPrimitive()) {
  33. if (value.isJsonObject()) {
  34.  
  35. createHashMapFromJsonString(value.toString(), row_num);
  36.  
  37. } else if (value.isJsonArray() && value.toString().contains(":")) {
  38.  
  39. ArrayList<String> list = new ArrayList<>();
  40. JsonArray array = value.getAsJsonArray();
  41. if (null != array) {
  42. for (JsonElement element : array) {
  43. createHashMapFromJsonString(element.toString(), row_num);
  44. }
  45. map.add(key+list);
  46. }
  47. }
  48. else if (value.isJsonArray() && !value.toString().contains(":"))
  49. {
  50. map.add(key+value.getAsJsonArray());
  51. }
  52. }
  53. else
  54. {
  55. map.add(key+value.getAsString());
  56. }
  57. }
  58. map.add(key+value.toString());
  59. System.out.println(key+":"+value+":"+row_num);
  60. }
  61.  
  62.  
  63. }
  64.  
  65. public static void main(String args[])
  66. {
  67. String json_input = "{"MedicationOrders":[{"AHFS":["28:08.08"]}]}";
  68. int row_num = 0;
  69. if(json_input.trim().charAt(0) == '[')
  70. {
  71. try
  72. {
  73. JSONArray jsonArray = new JSONArray(json_input);
  74. for (int i = 0; i < jsonArray.length(); i++)
  75. {
  76. JSONObject jsonobject = jsonArray.getJSONObject(i);
  77. String json = jsonobject.toString();
  78. createHashMapFromJsonString(json,row_num);
  79. row_num++;
  80. }
  81. }
  82. catch (JSONException e)
  83. {
  84. }
  85. }
  86. else
  87. {
  88.  
  89. createHashMapFromJsonString(json_input,row_num);
  90. }
  91.  
  92. }
  93. }
Add Comment
Please, Sign In to add comment