【问题标题】:How to convert string array to object using GSON/ JSON?如何使用 GSON/JSON 将字符串数组转换为对象?
【发布时间】:2013-07-31 12:15:16
【问题描述】:

我有一个这样的 json:

[
  [
    "Passport Number",
    "NATIONALITY",
    "REASONS"
  ],
  [
    "SHAIS100",
    "INDIA",
    ""
  ],
  [
    "",
    "",
    "Agent ID is not matched."
  ],
  [
    "",
    "",
    ""
  ]
]

我想将此填充到ArrayList<String[]>,请告诉我该怎么做?

并且空字符串不应转换为 null。

【问题讨论】:

标签: java json spring-mvc gson


【解决方案1】:

这很简单,您只需要执行以下操作:

1.- 首先创建Gson 对象:

Gson gson = new Gson();

2.- 然后为您的List<String[]> 获取通讯员Type(请注意,由于Java 的type erasure,您不能执行List<String[]>.class 之类的操作):

Type type = new TypeToken<List<String[]>>() {}.getType();

3.- 最后将JSON解析成type类型的结构:

List<String[]> yourList = gson.fromJson(yourJsonString, type);

【讨论】:

  • 类型类型 = new TypeToken>() {}.getType();它应该是 Type type = new TypeToken>() {}.getType();同样 List yourList = gson.fromJson(yourJsonString, type);它应该是 List yourList = gson.fromJson(yourJsonString, type);
【解决方案2】:

看看Gson docs

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

(Serialization)
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
==> ints2 will be same as ints

这对您很重要:我们还支持多维数组,具有任意复杂的元素类型

对于null 对象,Gson 默认不会转换为 null。 Ref. 但是,如果您想在之后进行扫描,您可以配置为扫描那些 nulls 属性。

Gson 中实现的默认行为是忽略空对象字段。这允许更紧凑的输出格式;但是,客户端必须为这些字段定义一个默认值,因为 JSON 格式会被转换回其 Java。

以下是配置 Gson 实例以输出 null 的方法:

Gson gson = new GsonBuilder().serializeNulls().create();

在您的问题中,您可能不需要配置它。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2021-10-04
    • 2018-11-16
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2017-01-24
    相关资源
    最近更新 更多