com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was

The exception reported:

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

Premise: The Android side uses retrofit to send network requests, and an error is reported when parsing the json data returned by the backend.

Reason: 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": "Saved successfully",

        "data":""

}

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

{

        "code":200,

        "msg": "Saved successfully",

        "data":{

                "text": "I'm dumbfounded"

        }

}

At this time, since data is an Object class , and the data returned by the backend is a string , the above error will be reported.

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 should be 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<UploadFileInfoResult> 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.

In general, the front-end and back-end communication is not in place.

Guess you like

Origin blog.csdn.net/qq_54087555/article/details/127423567