GSON returns an empty object

1,808 views
Skip to first unread message

JR

unread,
Jan 27, 2015, 5:32:32 PM1/27/15
to orient-...@googlegroups.com
Hi all,

I have a strange (really strange) problem with Gson and OrientDb. FYI, I'm using OrientDb v2.0, Gson 2.3.1

After retrieving a document from OrientDB, when I try to generate the corresponding JSON using GSON I get an empty object (I can see all the properties, they are just empty). 

But, if I do perform an access to one of the properties (Ex: String a = p.getName()) everything works perfectly.

I suspect there is something going on with attach/detach cause if I do a db.detach(object) "something" happen: all the properties appear correctly in the JSON but none of the LINKed properties is populated.

This is the code:



import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.object.db.OObjectDatabasePool;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;

public class Company {
@Expose private String name;
public Company() {
this.name = "";
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
public static void main(String[] argv) {
OObjectDatabaseTx db= OObjectDatabasePool.global().acquire("remote:localhost/Testing", "admin", "admin");
db.getEntityManager().registerEntityClass(Company.class);
ORecordId id = new ORecordId("#13:1");
Company p = db.load(id);
db.close();

               //If I remove this line, I get an empty json
System.out.println(p.getName());
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 
String res = gson.toJson(p);
System.out.println(res);
}

}




I also tried loading using SQL (List<Company> pRes = db.query(new OSQLSynchQuery<Company>("select from Company where @rid=#13:1"));) but same problem. 

Not sure what's going on, it seems something funny between Gson and OrientDB reflection but I don't know how to solve it.

Thanks!


JR

unread,
Jan 27, 2015, 10:10:37 PM1/27/15
to orient-...@googlegroups.com
Just found more details.

Imagine that the class has 2 properties. In my example it just has name but, it you add another property ex, description if you don't "visit" both properties gson doesn't populate both, just the one you visited.

In my example, if you add a property "description" and then you do only a System.out.println(p.getName()), gson will return 
{"name":"someName","description":""}

but if you do: System.out.println(p.getName()+" "+p.getDescription()); gson will return
{"name":"someName","description":"someDescription"}

I tried to use the built in ODocument.toJSON() but it's not powerful enough for what I need to do.

Thanks
Reply all
Reply to author
Forward
0 new messages