[英]Gson.toJson(Object) returning object hash code
我正在尝试使用Gson.ToJson(Object)
方法在下面转换此类,但是它重现了该类的对象哈希代码,例如: br.com.helpradar.entity.User@475fdaaa
但是,我可以毫无问题且具有所有关系地检索user.expertise: 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>();
}
这是我的Gson方法:
Gson gson = new GsonBuilder()
.registerTypeAdapter(User.class, new MyTypeAdapter<Expertise>())
.registerTypeAdapter(User.class, new MyTypeAdapter<Review>())
.create();
return gson.toJson(user);
这是我的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());
}
}
因此,如何使Gson.ToJson(user)
实际返回Json字符串,以便可以在另一端使用Gson.FromJson? 提前致谢。
我认为您需要使用方法enableComplexMapKeySerialization() 。 在这里,您可以查看下一个文档:
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...
和示例:
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));
输出将是:
{
"(5,6)": "a",
"(8,8)": "b"
}
因此,您可以这样尝试:
Gson gson = new GsonBuilder()
.registerTypeAdapter(User.class, new MyTypeAdapter<Expertise>())
.registerTypeAdapter(User.class, new MyTypeAdapter<Review>())
.enableComplexMapKeySerialization()
.create();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.