public static JsonObject fromMap(Map<?, ?> map) { JsonObject jsonObject = new JsonObject(); if (map != null) { for (Map.Entry<?, ?> mapEntry : map.entrySet()) { try { String mapKey = ObjectUtilities.toString(mapEntry.getKey()); JsonElement mapValue; if (mapEntry.getValue() instanceof JsonSerializable) { mapValue = fromPrimitive(((JsonSerializable) mapEntry.getValue()).serializeToJson()); } else if (mapEntry.getValue() instanceof Map) { mapValue = fromMap((Map<?, ?>) mapEntry.getValue()); } else if (mapEntry.getValue() instanceof List) { mapValue = fromArray((List) mapEntry.getValue()); } else { mapValue = fromPrimitive(mapEntry.getValue()); if (mapValue == null) mapValue = fromPrimitive(ObjectUtilities.toString(mapEntry.getValue())); } if (mapValue != null) jsonObject.add(mapKey, mapValue); } catch (Exception ex) { ex.printStackTrace(); } } } return jsonObject; }
public static JsonArray fromArray(List list) { JsonArray jsonArray = new JsonArray(); if (list != null) { for (Object listItem : list) { JsonElement jsonListItem; if (listItem instanceof List) jsonListItem = fromArray((List) listItem); else if (listItem instanceof Map) jsonListItem = fromMap((Map<?, ?>) listItem); else if (listItem instanceof JsonSerializable) jsonListItem = fromPrimitive(((JsonSerializable) listItem).serializeToJson()); else jsonListItem = fromPrimitive(listItem); jsonArray.add( jsonListItem == null ? new JsonPrimitive(ObjectUtilities.toString(listItem)) : jsonListItem); } } return jsonArray; }