简体   繁体   中英

gson custom convert json key to string

My server is returning json key-value pair like

{
    "my-name":"name"
}

I am using retrofit lib. So that gson is converting this to java object. So I created java object like below

public class Example{
    public String myname;  // cannot have my-name variable
}

response is giving me is "myname=null". Because variable in json is my-name but I cannot have same variable in java class. How to have same variable name like json in java?

You can add the @SerializedName("my-name") annotation to your POJO class like this:

public class Example{
   @SerializedName("my-name")
   public String myname;  // cannot have my-name variable
}

YOu can read more about this in the GSON documentation: https://sites.google.com/site/gson/gson-user-guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM