簡體   English   中英

Gson.toJson(Object)返回對象哈希碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM