0

I thought this would be a fairly simple and frequent issue, but it is surprisingly not, because I can't find any discussion around this topic online.

It's simple: Android's naming convention ensures that all member variable's name starts with "m", like "mId", "mName". I need to convert a json object to a Pojo using Gson. However the json object's field names do not start with "m" prefix. Hence it fails to convert.

I don't have control over the json format as it is a response from the internet. I also don't want to change all member variables in the project as there are a lot. Is there any work around so that I can still use Gson to do the conversion?

Also I have checked that Gson has FieldNamingPolicy that you can set to match the fields, but there're only 4 pre-defined policies and I can't figure out a way to add a customized one.

Thanks!

HeyThere
  • 307
  • 3
  • 16

1 Answers1

2

You can use annotations, but that means you still have to apply the changes to the whole project.

Like that:

@SerializedName("name")
@Expose
String mName;

It probably would end up being easier to re-write the POJOs. Also you can use websites like http://www.jsonschema2pojo.org/ to automatically create the classes with annotations for you.

And just FYI, the m is only a convention for code used on the AOSP. On your personal project you're free to use whatever you prefer and I personally hate the m convention and never ever ever use it. (Why do most fields (class members) in Android tutorial start with `m`?)

Community
  • 1
  • 1
Budius
  • 37,587
  • 15
  • 92
  • 134