1.安卓客户端发送post http请求,
Response response = HttpUtil.sendOkHttpRequest(APIConfig.BASE_URL + "/pay/getAll");
if (response != null) {
Gson gson=new Gson();
OrderRespData orderRespData= gson.fromJson(response.body().toString(), OrderRespData.class);
2.解析响应数据出现如下异常:
FATAL EXCEPTION: main
Process: com.example.hellochina, PID: 31020
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.google.gson.Gson.fromJson(Gson.java:801)
at com.google.gson.Gson.fromJson(Gson.java:773)
at com.example.hellochina.MainActivity.queryOrder(MainActivity.java:95)
at com.example.hellochina.MainActivity.access$100(MainActivity.java:23)
at com.example.hellochina.MainActivity$2.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:5610)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1213)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
3.原因分析:
OrderRespData orderRespData= gson.fromJson(response.body().toString(), OrderRespData.class); 使用toString()方法不正确,应该使用string(),即可正确解析json字符串
OrderRespData orderRespData= gson.fromJson(response.body().string(), OrderRespData.class);