GSON反序列化问题

发布于 2024-10-04 12:04:30 字数 1014 浏览 2 评论 0原文

我在使用 GSON 库时遇到反序列化问题。

以下是我尝试反序列化的 JSON 代码,

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

我创建了以下类

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
}

在调用 GSON 库后,数据为空。有什么想法课程有什么问题吗?

提前感谢您的帮助......我认为这是微不足道的......

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 ....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光病人 2024-10-11 12:04:30

@user523392 说:

成员变量必须与 JSON 响应中给出的内容完全匹配

但事实并非如此。

有几个选项可用于指定 Java 字段名称如何映射到 JSON 元素名称。

适用于上述原始问题中的情况的一种解决方案是使用 @SerializedName 非常明确地声明它映射到的 JSON 元素名称。

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

另一种方法是创建自定义 FieldNamingStrategy 来指定如何将 Java 成员名称转换为 JSON 元素名称。此示例将相同的名称映射应用于所有 Java 成员名称。这种方法不适用于上面的原始示例,因为并非所有 JSON 元素名称都遵循相同的命名模式 - 它们并不都以“@”开头,并且有些使用驼峰命名法而不是用“-”分隔名称部分'。构建 Gson 实例时将使用此 FieldNamingStrategy 实例 (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();
  }
}

管理 Java 字段名称如何映射到 JSON 元素名称的另一种方法是在构建 Gson 实例时指定 FieldNamingPolicy,例如 gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES );。然而,这也不适用于原始示例,因为它将相同的名称映射策略应用于所有情况。

@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.

べ繥欢鉨o。 2024-10-11 12:04:30

由于特殊字符@和-,上面的JSON响应无法被GSON反序列化。 GSON 基于反射,成员变量必须与 JSON 响应中给出的内容完全匹配。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文