2013-04-23 33 views
1

我有一個類,我只需要一個方法..所以我已經在方法中聲明它。在定義爲方法的類中使用Gson返回null

現在,當我嘗試從這個類轉換爲json使用gson我得到空。

我的代碼是這樣的:

private Response performGetClientDetails(HashMap<String, Object> requestMap) { 

     class ClientDetails { 
      String id; 
      String name; 
      String lastName; 
      int accoundId; 

      public ClientDetails(String id, String name, String lastName, int accoundId) { 
       this.id = id; 
       this.name = name; 
       this.lastName = lastName; 
       this.accoundId = accoundId; 
      } 
     } 

     ClientDetails clientDetails = new ClientDetails(client.getId(), client.getFirstName(), client.getLastName(), client.getAccount().getId()); 
     Gson gson = new Gson(); 
     return new Response(true, gson.toJson(clientDetails)); 
    } 

什麼返回null是這樣的:gson.toJson(clientDetails) ..其應該返回一個JSON字符串。

+0

什麼是空? 'performGetClientDetails'返回? 「Response」類所做的一些事情? Response的構造函數對第二個參數做了什麼? – 2013-04-23 20:45:13

+0

@mattb我編輯了帖子..請看看,謝謝。 – Hasan 2013-04-23 20:46:50

+0

@mattb幫助請.. – Hasan 2013-04-23 20:58:56

回答

5

根據GSON Docs

Gson can not deserialize {"b":"abc"} into an instance of B since the class B is an inner class. if it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.

public class InstanceCreatorForB implements InstanceCreator<A.B> { 
    private final A a; 
    public InstanceCreatorForB(A a) { 
    this.a = a; 
    } 
    public A.B createInstance(Type type) { 
    return a.new B(); 
    } 
} 

The above is possible, but not recommended.

由於您使用的一個非靜態內部類,GSON將無法序列化物體。

您可以嘗試使用第二種解決方案(不建議使用),或者直接聲明ClientDetails類,這樣可以很好地工作。

+0

非常感謝:)我已經創建了一個名爲「JsonClasses」的類,並將我需要的所有內部類作爲內部類來放置。這是一個好方法嗎? – Hasan 2013-04-23 21:12:25

+0

不客氣!那麼,我不認爲把內部類作爲一種好方法。這將阻礙你的工作聲明/獲取信息,並且始終在你的Json響應的根目錄上有'JsonClasses'。我認爲內部類在事件處理程序和枚舉中更有用。 – 2013-04-23 21:23:07

+0

知道了,謝謝!我是新來的Java,所以我試圖讓事情如何工作:) – Hasan 2013-04-23 21:26:58