Last active
April 18, 2020 17:02
-
-
Save sveinungkb/9073b3cadc6b61de2084 to your computer and use it in GitHub Desktop.
GSON Field naming policy taking Android m-prefix into account (e.g. mField and mHomeAddress).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package co.sveinung.utils; | |
import com.google.gson.FieldNamingStrategy; | |
import java.lang.reflect.Field; | |
import java.util.regex.Pattern; | |
/** | |
* Created by sveinung on 21.02.15. | |
*/ | |
public class AndroidFieldNamingPolicy implements FieldNamingStrategy { | |
private static final String JSON_WORD_DELIMITER = "_"; | |
@Override | |
public String translateName(final Field f) { | |
if (f.getName().startsWith("m")) { | |
return handleWords(f.getName().substring(1)); | |
} | |
else { | |
throw new IllegalArgumentException("Don't know how to handle field not starting with m prefix: " + f.getName()); | |
} | |
} | |
private final static Pattern UPPERCASE_PATTERN = Pattern.compile("(?=\\p{Lu})"); | |
private String handleWords(final String fieldName) { | |
String[] words = UPPERCASE_PATTERN.split(fieldName); | |
final StringBuffer sb = new StringBuffer(); | |
for (String word : words) { | |
if (sb.length() > 0) { | |
sb.append(JSON_WORD_DELIMITER); | |
} | |
sb.append(word.toLowerCase()); | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have json keys like "home_address" , can I use java field as
private String mHomeAddress;
using this ?