已解决com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but w

The correct solution to the com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was exception has been resolved, and the personal test is effective! ! !

insert image description here

Article directory

Error report

A friend in the fan group reported an error when he typed the code (at that time, his heart was cold for a moment, and he came to me for help, and then helped him solve it smoothly. By the way, I hope it can help more people encounter this bug. Friends who will not solve it), the error message is as follows:

insert image description here

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 34 path $.data

The Android side uses retrofit to send network requests, and an error is reported when parsing the JSON data returned by the backend.
The json data format returned by the backend is inconsistent with the json format required by the entity class defined on the Android side.

For example: the backend returns json data format:

{

    "code":200,

    "msg":"保存成功",

    "data":""

}

On the Android side, define the entity class to json data format:

{

    "code":200,

    "msg":"保存成功",

    "data":{

            "text":"傻眼了吧"

    }

}

Solution

The solution is as follows

insert image description here
The problem is easy to solve. If the front-end or the back-end change the entity class, the front-end and the front-end are consistent, but sometimes you are "not enough", such as a rookie who joined the job, That's me. If you dare not, then solve the problem yourself!
It is important to look at the format of the data returned by the backend. like:

My retrofit request, an interface method:

Call upload(@PartMap Map<String, RequestBody> params, @Part MultipartBody.Part[] dataFiles);
The UploadFileInfoResult class is the class that I convert the data returned by the backend into.

The first method: At this time, you can replace this class with the ResponseBody class in OkHttp, and view the returned data format in the request callback onResponse in debugger mode.

The second way, or you can also view network requests through the network profiler of Android studio, official website address: Check network traffic with network performance profiler | Android Developers | Android Developers

After knowing the data format returned by the backend, just redefine the received entity class.

Welfare

6 technical books will be sent home every week
due to the limited time and energy of the blogger, and there are too many private messages every day, so it is impossible for every fan to reply in time. You
can enter the community skirt or add the blogger’s WeChat
and click the link below
http:/ /t.csdn.cn/6kInJ

Guess you like

Origin blog.csdn.net/weixin_50843918/article/details/129680820