Gson获得复杂的数组值

时间:2017-02-13 14:35:44

标签: java rest gson crud

在过去的几个小时里,我正在使用REST和Gson。但现在我卡住了。

我有这段代码:

public class Main {

    OkHttpClient client = new OkHttpClient();

    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static void main(String[] args) throws IOException {
        Main example = new Main();
        String response = example.run("http://localhost/crud/api.php/contacts/");
        System.out.println(response);

        Gson gson = new Gson();
        Contact fetchedContacts = gson.fromJson(response, Contact.class);

        System.out.println( fetchedContacts.toString() );

    }
}

我的localhost apache服务器返回给我这个JSON

{
    "contacts":
    {
        "columns":
        [
            "id",
            "name",
            "email",
            "tel"
        ],
        "records":
        [
            [
                1,
                "Simon",
                "s@imon.de",
                "911"
            ],
            [
                2,
                "Ganter",
                "gan@t.er",
                "911"
            ]
        ]
    }
}

但对象是null。我现在这段代码不起作用。但是如何解决呢? 接下来要采取的步骤是什么?我还有一个班级来接受我的接触:

public class Contact {

    private String name;
    private String email;
    private String tel;

    public Contact(String name, String email, String tel) {
        this.name = name;
        this.email = email;
        this.tel = tel;
    }

1 个答案:

答案 0 :(得分:1)

Gson想要这个

{"name":"",  "email":"",  "tel":""} 

其他/ extra将为null。

似乎您需要学习更多PHP / MySQL或完全切换到您更熟悉的Web框架。

旁注:一旦您更正了API,Retrofit将是一个有用的Java库