该函数将用于从 url 以 HttpResponse 对象的形式获取数据。
public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}
上面的函数在这里被调用,我们使用 Apache 库 Class 接收一个字符串形式的 json。在下面的语句中,我们尝试从我们收到的 json 中制作简单的 pojo。
String jsonString =
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/ blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
jsonElementForJavaObject, JsonJavaModel.class);
这是一个用于传入 json 的简单 java 模型类。公共类 JsonJavaModel{ 字符串内容;字符串标题;这是一个自定义反序列化器:
public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel> {
@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
JsonDeserializationContext arg2) throws JsonParseException {
final JsonJavaModel jsonJavaModel= new JsonJavaModel();
JsonObject object = json.getAsJsonObject();
try {
jsonJavaModel.content = object.get("Content").getAsString()
jsonJavaModel.title = object.get("Title").getAsString()
} catch (Exception e) {
e.printStackTrace();
}
return jsonJavaModel;
}
包括 Gson 库和 org.apache.http.util.EntityUtils;