Skip to content

Instantly share code, notes, and snippets.

@ozzi-
Last active February 20, 2020 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozzi-/4a7603b8a19a7fd906e005b046203544 to your computer and use it in GitHub Desktop.
Save ozzi-/4a7603b8a19a7fd906e005b046203544 to your computer and use it in GitHub Desktop.
java pojo to json
// convert json string into pojo
public static Object getAsObject(String json, Class<?> objClass) throws Exception {
JsonParser jParser = new JsonParser();
JsonObject jObj = (JsonObject) jParser.parse(json);
Object obj = objClass.getDeclaredConstructor().newInstance();
Field[] fields = objClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> fieldType = fields[i].getType();
String fieldTypeName = fieldType.getName();
if(fieldTypeName.equals("java.lang.String")){
try {
String value = jObj.get(fieldName).getAsString();
field.set(obj, value);
}catch (Exception e) {}
}else if(fieldTypeName.equals("java.lang.Integer")||fieldTypeName.equals("int")){
try {
int value = jObj.get(fieldName).getAsInt();
field.set(obj, value);
}catch (Exception e) {}
}else if(fieldTypeName.equals("long")){
try {
long value = jObj.get(fieldName).getAsLong();
field.set(obj, value);
}catch (Exception e) {}
}else {
throw new Exception("Field Value is not string, int or long but "+fieldTypeName);
}
}
return obj;
}
// convert arraylist of pojos to json array
public static String getAsJSON(ArrayList<?> list) throws IllegalArgumentException, IllegalAccessException {
String json = "[";
for (Object object : list) {
json += JSONRef.getAsJSON(object) + ",";
}
json = json.length()>1?json.substring(0, json.length() - 1) : json;
return json + "]";
}
// convert pojo to json object
public static String getAsJSON(Object obj, boolean surpressObjCurlies) throws IllegalArgumentException, IllegalAccessException {
Class<? extends Object> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
String json = surpressObjCurlies?"":"{";
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
fields[i].setAccessible(true);
Object value = fields[i].get(obj);
if (value instanceof String) {
json += "\"" + name + "\":\"" + value + "\",";
}else if(value instanceof ArrayList<?>) {
json += "\"" + name + "\": [";
@SuppressWarnings("unchecked")
ArrayList<Object> arrList = (ArrayList<Object>) value;
for (Object arrListObj : arrList) {
if(arrListObj instanceof String) {
json += "\""+(String)arrListObj+"\",";
}else {
json += (String)arrListObj+",";
}
}
json = removeTrailingComma(json);
json += "]";
} else {
json += "\"" + name + "\":" + value + ",";
}
}
json = removeTrailingComma(json);
return json + (surpressObjCurlies?"":"}");
}
private static String removeTrailingComma(String json) {
json = json.endsWith(",")?json.substring(0, json.length() - 1) : json;
return json;
}
// convert resultset to json
public static String getAsJSONFromRS(ResultSet rs) throws SQLException {
String json = "[";
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
json+="{";
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
String value = rs.getString(name);
value = value==null?"null":value;
value = value.replaceAll("\r", "").replaceAll("\n", "\\\\n");
if(requiresQuotes(rsmd.getColumnType(i))) {
json+="\""+name+"\":\""+value+"\",";
}else {
json+="\""+name+"\":"+value+",";
}
}
json+="},";
json = json.substring(0, json.length() - 1);
}
json = json.length()>1?json.substring(0, json.length() - 1) : json;
return json + "]";
}
private static boolean requiresQuotes(int i) throws SQLException {
boolean requires = true;
if(i == java.sql.Types.INTEGER) {
requires=false;
}
if(i == java.sql.Types.BOOLEAN) {
requires=false;
}
if(i == java.sql.Types.BIGINT) {
requires=false;
}
if(i == java.sql.Types.BIT) {
requires=false;
}
if(i == java.sql.Types.DECIMAL) {
requires=false;
}
if(i == java.sql.Types.DOUBLE) {
requires=false;
}
if(i == java.sql.Types.FLOAT) {
requires=false;
}
if(i == java.sql.Types.DOUBLE) {
requires=false;
}
if(i == java.sql.Types.TINYINT) {
requires=false;
}
System.out.println(i+" REQ - "+requires);
return requires;
}
// convert result set to typed object list
public static <T> ArrayList<T> createFromRS(ResultSet s, Class<T> objClass) throws Exception {
T obj = objClass.getDeclaredConstructor().newInstance();
ArrayList<T> objs = new ArrayList<T>();
Field[] fields = objClass.getDeclaredFields();
while (s.next()) {
obj = objClass.getDeclaredConstructor().newInstance();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> fieldType = fields[i].getType();
String fieldTypeName = fieldType.getName();
if(fieldTypeName.equals("java.lang.String")){
try {
String value = s.getString(fieldName);
field.set(obj, value);
}catch (Exception e) { throw new Exception(e); }
}else if(fieldTypeName.equals("java.lang.Integer")||fieldTypeName.equals("int")){
try {
int value = s.getInt(fieldName);
field.set(obj, value);
}catch (Exception e) { throw new Exception(e); }
}else if(fieldTypeName.equals("long")){
try {
long value = s.getLong(fieldName);
field.set(obj, value);
}catch (Exception e) { throw new Exception(e); }
}else {
throw new Exception("Field Value is not string, int or long but "+fieldTypeName);
}
}
objs.add((T) obj);
}
return objs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment