編集
私の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());