【问题标题】:GSON fromJson with complex JSONObject not working具有复杂 JSONObject 的 GSON fromJson 不起作用
【发布时间】:2016-04-15 00:31:01
【问题描述】:

我正在尝试将 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 答案,它也有效!

【问题讨论】:

  • 几个小时后,问题是我需要这样做:Test[] data = gson.fromJson(jsonAll.get("tests").toString(), Test[].class );

标签: android json gson


【解决方案1】:

这是你必须做的。创建两个类Tests.javaTest.java

Tests.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());

【讨论】:

  • 完美。谢谢老哥!
【解决方案2】:

我认为您的问题可能出在: Test[] data = gson.fromJson(jsonAll.toString(), Test[].class);线,

我改成 Test[] data = gson.fromJson(jsonAll.get("tests").toString(), Test[].class); 它对我有用

解析器不知道在“测试”标签中查找数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多