简体   繁体   中英

Retrofit JSON Error parsing error

Retrofit gives me this error when I try to parse the following JSON response

Raw

[{"DeviceName":"Samsung Galaxy A5","Brand":"Samsung"...},{"DeviceName":"Samsung Galaxy A5 Duos"... ...]

Pretty JSON数据

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

@FormUrlEncoded
@PATCH("/v1/getphone/")
Call<List<Phone>> getPhoneInfo(@Field("device") String device);

Java Class

public class Phone {
@SerializedName("DeviceName")
@Expose
public String DeviceName;
@SerializedName("Brand")
@Expose
public String Brand;
@SerializedName("technology")
@Expose
public String technology;
....

Any help? Thanks

Put your Phone class inside another class as a list:

public class Root {

private List<Phone> phone;

//getters and setters here
}

and change this line:

Call<List<Phone>> getPhoneInfo(@Field("device") String device);

to

Call<Root> getPhoneInfo(@Field("device") String device);

In retrofit you need an array name to create a class with.your json is valid but the response doesn't have any array name so it won't be able to parse in that way.you have to parse it manually by getting json string from your response in retrofit like this

  ApiServiceClient.getApiService().yourFunctionName().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                try {
                    String jsonString=response.body().string();
                    Log.e(TAG, "onResponse: "+response.body().string());
                     //Parse your json here
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t) {

            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM