I'm trying to transform this class below using the Gson.ToJson(Object)
method, but it is returing me the object hash code of the class, eg: br.com.helpradar.entity.User@475fdaaa
However, I can retrieve the user.expertise without any problems and with all the relationships: Gson.ToJson(user.getExpertise)
@Entity
@SequenceGenerator(name="seqUser", sequenceName="SEQ_USER", allocationSize=1)
public class User {
@Id
private Long id;
@Column(nullable=false)
private String name;
@OneToOne
private Contact contact;
//enum
private TypeUser typeUser;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "USER_REVIEW",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "REVIEW_ID") })
@Column(name="REVIEW")
private Set<Review> review= new HashSet<Review>();
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "USER_EXPERTISE",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "EXPERTISE_ID") })
@Column(name="EXPERTISE")
private Set<Expertise> expertise = new HashSet<Expertise>();
}
This is my Gson method:
Gson gson = new GsonBuilder()
.registerTypeAdapter(User.class, new MyTypeAdapter<Expertise>())
.registerTypeAdapter(User.class, new MyTypeAdapter<Review>())
.create();
return gson.toJson(user);
This is my MyTypeAdapter:
class MyTypeAdapter<T> extends TypeAdapter<T> {
public T read(JsonReader reader) throws IOException {
return null;
}
public void write(JsonWriter writer, T obj) throws IOException {
if (obj == null) {
writer.nullValue();
return;
}
writer.value(obj.toString());
}
}
So, how do I get the Gson.ToJson(user)
to actually return a Json string so that I can use Gson.FromJson on my other end? Thanks in advance.
I think you need use method enableComplexMapKeySerialization() . Here you can see next documentation:
public GsonBuilder enableComplexMapKeySerialization()
Enabling this feature will only change the serialized form if the map
key is a complex type (i.e. non-primitive) in its serialized JSON form.
The default implementation of map serialization uses toString() on the key...
And example:
Gson gson = new GsonBuilder()
.register(Point.class, new MyPointTypeAdapter())
.enableComplexMapKeySerialization()
.create();
Map<Point, String> original = new LinkedHashMap<Point, String>();
original.put(new Point(5, 6), "a");
original.put(new Point(8, 8), "b");
System.out.println(gson.toJson(original, type));
Output will be:
{
"(5,6)": "a",
"(8,8)": "b"
}
So, you can try like this:
Gson gson = new GsonBuilder()
.registerTypeAdapter(User.class, new MyTypeAdapter<Expertise>())
.registerTypeAdapter(User.class, new MyTypeAdapter<Review>())
.enableComplexMapKeySerialization()
.create();
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.