user523392
user523392

Reputation: 47

GSON deserialization problem

I am having a deserialization problem using the GSON library.

The following is the JSON code which I try to deserialize

{"response": {
  "@service": "CreateUser",
  "@response-code": "100",
  "@timestamp": "2010-11-27T15:52:43-08:00",
  "@version": "1.0",
  "error-message": "",
  "responseData": {
    "user-guid": "023804207971199"
  }
}}

I create the following classes

public class GsonContainer {

        private GsonResponse mResponse;

        public GsonContainer() { }

        //get & set methods

}

public class GsonResponse {

    private String mService;
    private String mResponseCode;
    private String mTimeStamp;
    private String mVersion;
    private String mErrorMessage;

    private GsonResponseCreateUser mResponseData;

    public GsonResponse(){

    }

    //gets and sets method
}

public class GsonResponseCreateUser {

    private String mUserGuid;

    public GsonResponseCreateUser(){

    }

    //get and set methods
}

After calling the GSON library the data is null. Any ideas what is wrong with the classes?

Thx in advance for your help ... I assume it's something trivial ....

Upvotes: 3

Views: 5442

Answers (2)

Programmer Bruce
Programmer Bruce

Reputation: 66943

@user523392 said:

the member variables have to match exactly what is given in the JSON response

This is not the case.

There are a few options for specifying how Java field names map to JSON element names.

One solution that would work for the case in the original question above is to annotate the Java class members with the @SerializedName to very explicitly declare what JSON element name it maps to.

// output: [MyObject: element=value1, elementTwo=value2]

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class Foo
{
  static String jsonInput =
      "{" +
          "\"element\":\"value1\"," +
          "\"@element-two\":\"value2\"" +
      "}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    MyObject object = gson.fromJson(jsonInput, MyObject.class);
    System.out.println(object);
  }
}

class MyObject
{
  String element;

  @SerializedName("@element-two")
  String elementTwo;

  @Override
  public String toString()
  {
    return String.format(
        "[MyObject: element=%s, elementTwo=%s]",
        element, elementTwo);
  }
}

Another approach is to create a custom FieldNamingStrategy to specify how Java member names are translated to JSON element names. This example would apply the same name mapping to all Java member names. This approach would not work for the original example above, because not all of the JSON element names follow the same naming pattern -- they don't all start with '@' and some use camel case naming instead of separating name parts with '-'. An instance of this FieldNamingStrategy would be used when building the Gson instance (gsonBuilder.setFieldNamingStrategy(new MyFieldNamingStrategy());).

class MyFieldNamingStrategy implements FieldNamingStrategy
{
  // Translates the field name into its JSON field name representation.
  @Override
  public String translateName(Field field)
  {
    String name = field.getName();
    StringBuilder translation = new StringBuilder();
    translation.append('@');
    for (int i = 0, length = name.length(); i < length; i++)
    {
      char c = name.charAt(i);
      if (Character.isUpperCase(c))
      {
        translation.append('-');
        c = Character.toLowerCase(c);
      }
      translation.append(c);
    }
    return translation.toString();
  }
}

Another approach to manage how Java field names map to JSON element names is to specify a FieldNamingPolicy when building the Gson instance, e.g., gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);. This also would not work with the original example, however, since it applies the same name mapping policy to all situations.

Upvotes: 11

user523392
user523392

Reputation: 47

The JSON response above cannot be deserialized by GSON because of the special characters @ and -. GSON is based on reflections and the member variables have to match exactly what is given in the JSON response.

Upvotes: 0

Related Questions