How to parse dynamic JSON with Retrofit?

送分小仙女□ 提交于 2019-11-28 09:43:52

问题


I have dynamic JSON, here is example: http://pastebin.com/QMWRZTrD

How I can parse it with Retrofit?

I failed to generate POJO classes, since I have dynamic fields like "5411" and "5412".

EDIT:

I solved it by using Map, since first value is always integer, and second is list of objects.

@FormUrlEncoded
@POST("history.php")
Observable<Map<Integer, List<Vehicle>>> getHistory(@Field("uredjaji") String vehicleId, @Field("startDate") String startDATE, @Field("endDate") 

回答1:


you can use Map to serialize and deserialize it in case of Random keys. Observable<Map<Integer, List<YourObject>>>




回答2:


You can get retrofit api call to return String in your RestApi Interface like

Call<String> method(@Path(..)...);

And for that to work you would need to add the scalars converter factory to where you create your Retrofit object. First you would need to import it:

compile  'com.squareup.retrofit2:converter-scalars:2.1.0'

And then add it:

Retrofit retrofit = new Retrofit.Builder()  
    .addConverterFactory(ScalarsConverterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .baseUrl("https://your.base.url/")
    .build();

And then in onResponse

public void onResponse(Call<String> call, Response<String> response) {
    if (response.isSuccessful()) {
        Type mapType = new TypeToken<Map<String,List<SomeClass>>() {}.getType(); // define generic type
        Map<String,List<SomeClass>> result= gson.fromJson(response.body(), mapType);
    } else {

    }
}

Also,check out this site it has great tutorials on Retrofit.



来源:https://stackoverflow.com/questions/41856975/how-to-parse-dynamic-json-with-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!