Nastaran Dousti
Nastaran Dousti

Reputation: 1

How to parse response of Retrofit with two Json object?

I can't find the solution to my problem.When I send data to server it works right but I can't get the results from the same method.

This is my JSON response:

{"ok":"true","msg":"active","data":{"_id":"1","name":"aaa","code":1111,"status":1,"updated_at":"2018-04-03 07:26:56","created_at":"2018-04-03 07:17:05","key":"mmnnjmn34564lt"}}

I can get the results such as "ok" and "msg" but I can't get the "data" field. How I can solve it??

Interface:

public interface ApiInterfaceService {

@POST("active")
Call<Data> createConfirmCode(@Body Data data);

OkHttpClient okHttpClient=new OkHttpClient();
    Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(ApiClientConfig.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    apiInterfaceService =retrofit.create(ApiInterfaceService.class);
 }

Data.java

public class Data {

@SerializedName("ok")
public String ok;

@SerializedName("msg")
private String msg;

@SerializedName("data")
private List<dataResponse> data;
}

dataResponse.java

public class dataResponse{

@SerializedName("_id")
public Integer _id;

@SerializedName("name")
public String name;


@SerializedName("code")
public Integer code;

@SerializedName("status")
public Integer status;
}

my code:

    Data datamodel=new Data();
    Call<Data> call = apiInterfaceService.createConfirmCode(datamodel);
    call.enqueue(new Callback<Data>() {
        @Override
        public void onResponse(Call<Data> call, Response<Data> response) {
            if (response.isSuccessful()) {

     Log.i(InitialClass.TAG,String.valueOf(response.body().getMsg()+" "+response.body().getData());
            }
        }
        @Override
        public void onFailure(Call<Data> call, Throwable t) {
            Log.i(InitialClass.TAG,t.getMessage()+" "+ t.getCause());
        }
    });

Upvotes: 0

Views: 467

Answers (1)

Samuel Eminet
Samuel Eminet

Reputation: 4737

You json looks malformed, copy paste it to http://jsonviewer.stack.hu/ and format it to see the format json from the string you provided to us, if this is really the json you received, problem is not on android side but on server side.

Edit with new json, it seems your are requesting a array

@SerializedName("data")
private List<dataResponse> data;

But your json returning a object

"data": {
    "_id": "1",
    "name": "aaa",
    "code": 1111,
    "status": 1,
    "updated_at": "2018-04-03 07:26:56",
    "created_at": "2018-04-03 07:17:05",
    "key": "mmnnjmn34564lt"
  }

Upvotes: 1

Related Questions