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

时间:2014-10-15 04:54:10

标签: java json gson

我尝试使用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? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

我认为你需要使用方法 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();