我正在尝试将 GSON fromJson() 与简单的 JSONObject 一起使用,但由于某种原因它无法正常工作。而且它根本不打印任何堆栈跟踪。也许我在我的代码中做错了一些事情,有人可以提供帮助:
JSONObject json = new JSONObject();
json.put("id", "1");
json.put("name", "Test 1");
JSONObject json2 = new JSONObject();
json2.put("id", "2");
json2.put("name", "Test 2");
JSONArray array = new JSONArray();
array.put(json);
array.put(json2);
JSONObject jsonAll = new JSONObject();
jsonAll.put("tests", array );
Gson gson = new Gson();
Test[] data = gson.fromJson(jsonAll.toString(), Test[].class);
还有我的测试类:
public class Test {
public String id;
public String name;
public Test(String id, String name){
this.id = id;
this.name = name;
}
}
我试图在 Android 中解析它,但它不工作或打印错误..
已解决:
Test[] data = gson.fromJson(jsonAll.get("tests").toString(), Test[].class);
或者使用 K Neeraj Lal 答案,它也有效!
最佳答案
这是你必须做的。创建两个类 Tests.java
和 Test.java
。
测试.java
public class Tests {
List<Test> tests;
public List<Test> getTests() {
return tests;
}
public void setTests(List<Test> tests) {
this.tests = tests;
}
}
Test.java(您的测试类)
public class Test {
public String id;
public String name;
public Test(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
现在使用Gson
解析数据如下,
Tests data = new Gson().fromJson(jsonAll.toString(), Tests.class);
Log.e("Parsed Data", data.getTests().toString());
关于android - 具有复杂 JSONObject 的 GSON fromJson 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36628427/