GSON 使用成员数组列表<String>反序列化对象



我见过很多类似的问题。我无法找到任何适合我的确切问题。在所有示例中,我发现 List 是父类中定义的对象类型,而我只有一个字符串列表。我尝试使用一个简单的数组 String[],并且我看到了重载反序列化程序和获取 TypeToken 的示例,但我无法将其绑定在一起以使其工作。我的列表总是空的(如果我在定义列表时不初始化它,则为 null(。我在这里错过了什么,感觉就像我试图做一些非常简单的事情,但我在上面找到的所有东西看起来都过于复杂。

这是我的班级:

public class MondoConfig {
private String merchantURL;
public ArrayList<String> targets = new ArrayList<String>();

public MondoConfig () {}
public String getMerchantURL() {
return this.merchantURL;
}
public void setMerchantURL(String url) {
this.merchantURL = url;
}
public ArrayList<String> getTargets() {
return this.targets;
}
public void setTargets(ArrayList<String> t) {
this.targets = t;

}
}

这是我的json:

{
"merchantURL":"https://example.com/collections/posters",
"targets":[
"testing",
"another",
"one more"
]
}

和我的代码反序列化:

BufferedReader br = new BufferedReader(new FileReader("C:\mondo_config.json"));
MondoConfig config = gson.fromJson(br, MondoConfig.class);

我在您的代码中看到了一些问题,但我能够让它正常工作而没有任何问题。

package org.nuttz.gsonTest;
import java.util.ArrayList;
public class MondoConfig {
private String merchantURL;
public ArrayList<String> targets = new ArrayList<String>();
MondoConfig () {}
public String getMerchantURL() {
return this.merchantURL;
}
public void setMerchantURL(String url) {
this.merchantURL = url;
}
public ArrayList<String> getTargets() {
return this.targets;
}
public void setTargets(ArrayList<String> t) {
this.targets = t;
}
}

原始代码中的 setMerchantURL(( 函数不太正确,所以我修复了它。然后我用这段代码来测试它:

package org.nuttz.gsonTest;
import java.io.*;
import java.util.List;
import com.google.gson.*;
public class App 
{
public static void main( String[] args )
{
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("/home/jim/mondoconfig.json"));
MondoConfig config = gson.fromJson(br, MondoConfig.class);
System.out.println("Contents of config:");
System.out.println(config.getMerchantURL());
List<String> targets = config.targets;
for (String t : targets) {
System.out.println(t);
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}

并得到以下结果:

Contents of config:
https://example.com/collections/posters
testing
another
one more

这是使用GSON的2.8.2版本。换句话说,你走在正确的轨道上,你只需要修复MondoConfig类。

相关内容

最新更新