本文主要是介绍gson 与 SerializedName : 修改json生成的bean类字段名称,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import org.junit.Test/*** SerializedName* 修改json字段名称*/
data class UserNaming(@SerializedName("Name")var name: String,@SerializedName("email_of_developer")var emailOfDeveloper: String,@SerializedName("isDeveloper")var isDeveloper: Boolean,@SerializedName("_ageOfDeveloper")var ageOfDeveloper: Int,var numStr: String
)class ExampleUnitTest2 {@Testfun test1() {val builder = GsonBuilder()builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)val gson = builder.create()//json多一个haha字段val jsonStr ="{\"haha\":\"666\",\"Name\":\"name\",\"email_of_developer\":\"email\"," +"\"isDeveloper\":true,\"_ageOfDeveloper\":26}"println("usersJson===$jsonStr")val userNaming = gson.fromJson(jsonStr, UserNaming::class.java)println("usersBean===$userNaming")}//usersJson==={"haha":"666","Name":"name","email_of_developer":"email","isDeveloper":true,"_ageOfDeveloper":26}//usersBean===UserNaming(name=name, emailOfDeveloper=email, isDeveloper=true, ageOfDeveloper=26, numStr=null)@Testfun test2() {val builder = GsonBuilder()builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)val gson = builder.create()//json少字段val jsonStr ="{\"email_of_developer\":\"email\",\"isDeveloper\":true,\"_ageOfDeveloper\":26}"println("usersJson===$jsonStr")val userNaming = gson.fromJson(jsonStr, UserNaming::class.java)println("usersBean===$userNaming")}//usersJson==={"email_of_developer":"email","isDeveloper":true,"_ageOfDeveloper":26}//usersBean===UserNaming(name=null, emailOfDeveloper=email,// isDeveloper=true, ageOfDeveloper=26, numStr=null)}
这篇关于gson 与 SerializedName : 修改json生成的bean类字段名称的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!