简体   繁体   English

Gson.fromJson(String, Class) 如何工作?

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

Consider following sample Json string :考虑以下示例 Json 字符串:

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

I convert the above Json to the following pojo :我将上面的 Json 转换为以下 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 ? json 对象中的键如何跟踪到我的 pojo 中的变量? How is the value of the key FatherName stored in father in Info.class ?如何是关键的价值FatherName存储在fatherInfo.class

Gson is using the reflection( https://android.jlelse.eu/reflections-on-reflection-performance-impact-for-a-json-parser-on-android-d36318c0697c ). Gson 正在使用反射( 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因此示例 json 将无法在您的示例中按预期工作,有几个选项可以解决此问题

  1. Change json string to {"name":"val","father":"val","mother":"val"}将 json 字符串更改为 {"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更改 info 类中的属性father-fatherName 和 Mother 3 Create a custom serializer GSON - Custom serializer in specific case

Thanks to @Aaron感谢@Aaron

you can also annotated the variables with @SerializedName您还可以使用@SerializedName 注释变量

@SerializedName("father") private string FatherName; @SerializedName("father") 私有字符串FatherName;

In Kotlin, having this class:在 Kotlin 中,有这个类:

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):我可以使用(其中 dataObteined 是 UsuariosDTO 类型):

val json = gson.toJson(dataObtained)

And later deserialize the json like this:然后像这样反序列化json:

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

After looking everywhere I found out my error was UsuariosDTO.class.到处寻找后,我发现我的错误是 UsuariosDTO.class。 Since Gson is a java library you have to use UsuariosDTO::class.java由于 Gson 是一个 Java 库,因此您必须使用 UsuariosDTO::class.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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