This is my POJO class
public class ResourceRecord {
public ResourceRecord() {}
public String name;
public Integer ttl;
public String type;
public String rr;
@SerializedName("class")
public String dnsClass;
}
And this the serialisation:
ResourceRecord rr = new ResourceRecord() {
{
name = "8.8.8.8";
dnsClass = "IN";
ttl = 600;
rr = "0431shangmao.com.";
type = "A";
}
};
String rrStr = new Gson().toJson(rr);
Apparently, rrStr
gets null
. Why?
I tried annotating the fields with @Expose
but the result stayed the same.
UPDATE: I changed to constructing to:
ResourceRecord rr = new ResourceRecord("8.8.8.8", 900,"A","1.dnstest.netshade.net.", "IN");
and it worked.
The reason why it didn't work is because you were creating anonymous innerclass of ResourceRecord
when you instantiate using curly braces:
ResourceRecord rr = new ResourceRecord() {
{
name = "8.8.8.8";
dnsClass = "IN";
ttl = 600;
rr = "0431shangmao.com.";
type = "A";
}
};
And Gson doesn't support serializing anonymous subclasses.
Try this,
Gson gson = new GsonBuilder().create(); String json = gson.toJson(obj);
obj is the object of pojo class
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.