简体   繁体   中英

Converting JSON objects in Android with gson

I am new to Java and Android so please bear with me. I am trying to create a function which calls a wcf service and converts the returned result from JSON to a Java object (I pass the type as the object t ), but it's throwing a null pointer exception on t , which must be null as I just want to pass an object of the correct type so that it becomes filled when converted. Kindly help me with it.

    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;

Thanks a lot.

After some tries, I ended up with this code but I am still facing a null pointer exception.

    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);

As far as I know, this is impossible. In order for one to do this, gson would have to be able to detect the correct class only from the serialized string . However, a single string can be interpreted in many valid ways. For instance, take an example on the gson website:

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

Using Gson.toJson on an instance of this class results in the string:

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

However, if I made another class identical to the first in all respects but name:

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

Then this would also serialize to the same string:

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

My point is that given a single string like {"value1":1,"value2":"abc"} , there is no way for gson to determine whether it should deserialize it into an object of type BagOfPrimitives or type SackOfPrimitives . Therefore, you always have to provide gson with the correct type, because it wouldn't be possible for gson to figure it out by itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM