gpt4 book ai didi

java - Gson.toJson(Object) 返回对象哈希码

转载 作者:行者123 更新时间:2023-11-30 03:43:08 25 4
gpt4 key购买 nike

我尝试使用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()Here您可以查看下一个文档:

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();

关于java - Gson.toJson(Object) 返回对象哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26374716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com