How to parse dynamic JSON with Retrofit?

前端 未结 2 1955
一向
一向 2020-12-21 13:33

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

相关标签:
2条回答
  • 2020-12-21 14:22

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

    0 讨论(0)
  • 2020-12-21 14:22

    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.

    0 讨论(0)
提交回复
热议问题