Gson获取复杂数组值
Gson get complex array values
在过去的几个小时里,我一直在使用 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() );
}
}
我的本地 Apache 服务器 return 我这个 JSON
{
"contacts":
{
"columns":
[
"id",
"name",
"email",
"tel"
],
"records":
[
[
1,
"Simon",
"s@imon.de",
"911"
],
[
2,
"Ganter",
"gan@t.er",
"911"
]
]
}
}
但是对象是null
。我现在这段代码不起作用。但是如何解决呢?
接下来要采取什么步骤?我的联系人也有一个 class:
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;
}
Gson 想要这个
{"name":"", "email":"", "tel":""}
任何其他/额外的内容都将为空。
看来您需要学习更多 PHP / MySQL 或完全切换到您更熟悉的 Web 框架。
旁注:一旦 API 更正
,Retrofit 将是一个有用的 Java 库
在过去的几个小时里,我一直在使用 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() );
}
}
我的本地 Apache 服务器 return 我这个 JSON
{
"contacts":
{
"columns":
[
"id",
"name",
"email",
"tel"
],
"records":
[
[
1,
"Simon",
"s@imon.de",
"911"
],
[
2,
"Ganter",
"gan@t.er",
"911"
]
]
}
}
但是对象是null
。我现在这段代码不起作用。但是如何解决呢?
接下来要采取什么步骤?我的联系人也有一个 class:
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;
}
Gson 想要这个
{"name":"", "email":"", "tel":""}
任何其他/额外的内容都将为空。
看来您需要学习更多 PHP / MySQL 或完全切换到您更熟悉的 Web 框架。
旁注:一旦 API 更正
,Retrofit 将是一个有用的 Java 库