有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用gson在Android中转换JSON对象

我不熟悉Java和Android,所以请耐心听我说。我试图创建一个调用wcf服务的函数,并将JSON返回的结果转换为Java对象(我将类型作为对象t传递),但它在t上抛出一个空指针异常,该异常必须是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);

共 (1) 个答案

  1. # 1 楼答案

    据我所知,这是不可能的。为了做到这一点,gson必须只能从序列化字符串中检测正确的类。然而,单个字符串可以用许多有效的方式进行解释。例如,以gson网站为例:

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

    在这个类的实例上使用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类型的对象。因此,您必须始终为gson提供正确的类型,因为gson不可能自己找到它