Чечил Крым Чечил Крым - 2 months ago 7
JSON Question

What techniques do you use to handle different JSON structure?

Retrofit call:

@GET("getUser")
Call<Map<Object,Object>> getUser(@Query("phoneNumber") String phoneNumber, @Query("hash") String hash)


I need json resut from browser, if return User object:

{"error":"0","value":[{"id":1,"name":"","phoneNumber":"87472335578","smsCode":497797,"smsCodeDate":1475160867,"hash":"76dcc911e14f997189243f3370080e62","roles":[{"id":2,"name":"ROLE_USER"}]}]}


and json resut from browser, if return error:

{"error":"-1"}


Callback response in android

enter image description here

For this issue
I used
Map<Object,Object>
to handle with different JSON structures. But the problem is in casting of numbers. I need int or long while java sees it as double value. I could use some parse methods. But in case of many variables in Map, that would be terrible work.

I can't use
Map<String,String>
and then parse it, because Gson doesn't want to process it. There is backslashes. Of course, it is obvious to remove them, but I would like to find elegant way to handle with JSON.

Code of json generator at server

public final static String SUCCESS = "0";
public final static String NOT_FOUND = "-1";

Map<Object, Object> m = new HashMap<>();

@RequestMapping("/getUser")
Map<Object, Object> getUser(@RequestParam(value = "phoneNumber", defaultValue = "") String phoneNumber,
@RequestParam(value = "hash", defaultValue = "") String hash) {

m.clear();

User user = userRepository.findByPhoneNumberAndHash(phoneNumber, hash);
if (user != null) {
m.put(ERROR_JSON, SUCCESS);
m.put(VALUE_JSON, String.valueOf(user));
} else {
m.put(ERROR_JSON, NOT_FOUND);
}
return m;
}


Above method returns this json:

{"error":"0","value":[{\"id\":\"1\",\"name\":\"\",\"phoneNumber\":\"87472335578\",\"smsCode\":497797,\"smsCodeDate\":1475160867,\"hash\":\"76dcc911e14f997189243f3370080e62\",\"roles\":[{\"id":2,\"name\":\"ROLE_USER\"}]}]}


original post

Answer

Follow http://wiki.workassis.com/android-retrofit-2-1-http-client/ this tutorial and use the following as your model class

class Result{
    String error;
    List<Value> value;
}

class Value{
    int id;
    String name;
    String phoneNumber;
    String smsCode;
    Long smsCodeDate;
    String hash;
    List<Roles> roles;

}

class Roles{
    int id;
    String name;
}

and use

@GET("getUser")
Call<Result>getUser(@Query("phoneNumber") String phoneNumber, @Query("hash") String hash)