Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active November 19, 2021 16:08
Show Gist options
  • Save EduardoSP6/3a3d8abd7a699ad50040b3a6b309b77e to your computer and use it in GitHub Desktop.
Save EduardoSP6/3a3d8abd7a699ad50040b3a6b309b77e to your computer and use it in GitHub Desktop.
Convert realm object to json
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import io.realm.RealmObject;
/**
* Convert realm object to json
* Author: Eduardo Sales
* Date: Nov, 10 2021
*/
public class RealmJsonAdapter {
public JSONObject toJson(Class<? extends RealmObject> modelClass, Object realmObject, ArrayList<String> fieldsIgnored, Boolean snakeCase) {
JSONObject jsonObject = new JSONObject();
boolean ignore = fieldsIgnored != null && fieldsIgnored.size() > 0;
ArrayList<String> fields = this.getFieldNames(modelClass);
try {
for (String fieldName : fields)
{
if (this.isConstant(fieldName)) {
continue;
}
if (ignore && fieldsIgnored.contains(fieldName)) {
continue;
}
String methodName = "get"+ this.strCapital(fieldName);
Method method = modelClass.getMethod(methodName);
String jsonName = (snakeCase ? this.strSnake(fieldName) : fieldName);
jsonObject.put(
jsonName,
method.invoke(realmObject)
);
}
} catch (JSONException
| NoSuchMethodException
| InvocationTargetException
| IllegalAccessException e) {
e.printStackTrace();
}
return jsonObject;
}
/** get property names of a class **/
private ArrayList<String> getFieldNames(Class<? extends RealmObject> modelClass) {
ArrayList<String> fields = new ArrayList<>();
for (Field f: modelClass.getDeclaredFields()) {
fields.add(f.getName());
}
return fields;
}
/** capitalize string **/
private String strCapital(String str) {
String retStr = str;
try {
// We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}
/** convert string to snake_case **/
private String strSnake(final String camelStr) {
StringBuilder stringBuilder = new StringBuilder();
for (char c : camelStr.toCharArray()) {
if (Character.isUpperCase(c)) {
stringBuilder.append('_').append(c);
} else {
stringBuilder.append(c);
}
}
return stringBuilder.toString().toLowerCase();
}
/** check if string is a model constant **/
private boolean isConstant(String s) {
for (char c : s.toCharArray()) {
if (c == '_') {
continue;
}
if(! Character.isUpperCase(c)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment