Java Gson将子项反序列化为父项中的字符串

Java Gson将子项反序列化为父项中的字符串,java,json,serialization,gson,Java,Json,Serialization,Gson,我正在尝试反序列化此json响应: { "_index":"miracle", "_type":"user", "_id":"AVpbIYg7NtDacQRf2Gz5", "_score":1.0, "_source": { "username":"andrei23", "password":"andrei_23" } } 我试过类似的方法,但不起作用: public class HitDTO {

我正在尝试反序列化此json响应:

{  
    "_index":"miracle",
    "_type":"user",
    "_id":"AVpbIYg7NtDacQRf2Gz5",
    "_score":1.0,
    "_source":
    {  
        "username":"andrei23",
        "password":"andrei_23"
    }
}
我试过类似的方法,但不起作用:

public class HitDTO {

    @SerializedName("_id")
    private String id;

    @SerializedName("_source")
    private String source;
}

是否有我可以使用的某种注释或其他注释?

首先,您需要为字段创建setter和getter

然后,封装JSON对象。因此,请按如下方式编辑您的类:

public class HitDTO {

   @SerializedName("_id")
   private String id;

   @SerializedName("_source")
   private HitSourceDTO source;

   // getters and setters
}

最后,添加一个函数以返回所请求的_源字段格式:

function String getStringOfSource()
{
   return "username=" + source.username + " password=" + source.password;
}
希望它能帮助你

编辑:我为此搜索了任何类型的注释,但没有找到完全符合您要求的注释

function String getStringOfSource()
{
   return "username=" + source.username + " password=" + source.password;
}