编辑
使用我的 GSON 示例中的数据模型。现在你可以这样做:
String response = "{\"response\":{\"numFound\":5,\"start\":0,\"docs\":[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4},{\"id\":5}]}}";
ObjectMapper mapper = new ObjectMapper();
ObjectReader objectReader = mapper.reader(Body.class);
Body body = (Body) objectReader.readValue(response);
System.out.println(body.getResponse().getDocs());
GSON 示例
您应该使用GSON到 JSON 解析。创建可帮助您使用“响应”字符串的数据模型。看我的例子:
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class SourceCodeProgram {
public static void main(String[] args) throws Exception {
String response = "{\"response\":{\"numFound\":5,\"start\":0,\"docs\":[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4},{\"id\":5}]}}";
Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println("To JSON");
System.out.println(gson.toJson(createTestBody()));
System.out.println("From JSON");
System.out.println(gson.fromJson(response, Body.class));
}
private static Body createTestBody() {
Response response = new Response();
response.setNumFound(5);
response.setStart(0);
response.setDocs(Arrays.asList(new Doc(1), new Doc(2), new Doc(3),
new Doc(4), new Doc(5)));
Body body = new Body();
body.setResponse(response);
return body;
}
}
class Body {
private Response response;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
@Override
public String toString() {
return "Body [response=" + response + "]";
}
}
class Response {
private int numFound;
private int start;
private List<Doc> docs;
public int getNumFound() {
return numFound;
}
public void setNumFound(int numFound) {
this.numFound = numFound;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
@Override
public String toString() {
return "Response [numFound=" + numFound + ", start=" + start
+ ", docs=" + docs + "]";
}
}
class Doc {
private int id;
public Doc() {
}
public Doc(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return Integer.toString(id);
}
}
输出:
To JSON
{"response":{"numFound":5,"start":0,"docs":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]}}
From JSON
Body [response=Response [numFound=5, start=0, docs=[1, 2, 3, 4, 5]]]
您可以通过以下方式检索“文档”:
Body body = gson.fromJson(response, Body.class);
System.out.println(body.getResponse().getDocs());