簡體   English   中英

使用gson在Android中轉換JSON對象

[英]Converting JSON objects in Android with gson

我是Java和Android的新手,請耐心等待。 我正在嘗試創建一個函數,該函數調用wcf服務並將返回的結果從JSON轉換為Java對象(我將類型作為對象t傳遞),但是它在t上引發了null指針異常,因為我必須為null只想傳遞正確類型的對象,以便在轉換時將其填充。 請幫助我。

    public static String Post(String serviceURL, Map<String, String> entites,
        Class<?> t) {
    String responseString = "";
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);


            Gson gson = new GsonBuilder().create();
            //now we will try to convert the class to the specified type.
            t = (Class<?>) gson.fromJson(responseString, t);



    } catch (Exception e) {

        responseString = e.toString();

    }
    return responseString;

非常感謝。

經過一番嘗試,我最終得到了這段代碼,但是我仍然面臨着空指針異常。

    MemberInfo mem = new MemberInfo();

    TypeToken<MemberInfo> m = null ;
    ServiceCaller.Post(getString(R.string.LoginService), values , m);


            Gson gson = new GsonBuilder().create();
            //now we will try to convert the class to the specified type.
            t = (TypeToken<T>) gson.fromJson(responseString, (Type) t);

據我所知,這是不可能的。 為了做到這一點,gson必須只能從序列化的string中檢測出正確的類。 但是,可以以許多有效方式解釋單個字符串。 例如,在gson網站上舉個例子:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  BagOfPrimitives() {
    // no-args constructor
  }
}

Gson.toJson的實例上使用Gson.toJson導致字符串:

{"value1":1,"value2":"abc"}

但是,如果除名稱之外,我在其他方面都使第一堂課與第一堂課相同:

class SackOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  SackOfPrimitives() {
    // no-args constructor
  }
}

然后,這還將序列化為相同的字符串:

{"value1":1,"value2":"abc"}

我的觀點是,給定單個字符串,例如{"value1":1,"value2":"abc"} ,gson無法確定應將其反序列化為BagOfPrimitives類型SackOfPrimitives BagOfPrimitives類型的SackOfPrimitives 因此,您始終必須為gson提供正確的類型,因為gson不可能自己弄清楚它的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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