简体   繁体   中英

How does Gson.fromJson(String, Class) work?

Consider following sample Json string :

{"Name":"val","FatherName":"val","MotherName":"val"}

I convert the above Json to the following pojo :

public class Info{
    private String name;
    private String father;
    private String mother;
}

What I am wondering is, when I do the following :

Gson.fromJson(jsonLine, Info.class);

How are the keys in json object tracked to the variables in my pojo ? How is the value of the key FatherName stored in father in Info.class ?

Gson is using the reflection( https://android.jlelse.eu/reflections-on-reflection-performance-impact-for-a-json-parser-on-android-d36318c0697c ). So the example json will not work as expected in your example there are a couple of option to solve this

  1. Change json string to {"name":"val","father":"val","mother":"val"}
  2. Change the properties in the info class father-fatherName and the same for mother 3 Create a custom serializer GSON - Custom serializer in specific case

Thanks to @Aaron

you can also annotated the variables with @SerializedName

@SerializedName("father") private string FatherName;

In Kotlin, having this class:

import com.google.gson.annotations.SerializedName

data class UsuariosDTO (
@SerializedName("data") var data: List<Usuarios>
    )
data class Usuarios(
@SerializedName("uid") var uid: String,
@SerializedName("name") var name: String,
@SerializedName("email") var email: String,
@SerializedName("profile_pic") var profilePic: String,
@SerializedName("post") var post: Post
)
data class Post(
@SerializedName("id") var id: Int,
@SerializedName("date") var date: String,
@SerializedName("pics") var pics: List<String>
)

I'm able to use (where dataObteined is of UsuariosDTO type):

val json = gson.toJson(dataObtained)

And later deserialize the json like this:

val offUsuariosDTO = gson.fromJson(json, UsuariosDTO::class.java)

After looking everywhere I found out my error was UsuariosDTO.class. Since Gson is a java library you have to use UsuariosDTO::class.java

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