【问题标题】:How to parse dynamic JSON with Retrofit?如何使用 Retrofit 解析动态 JSON?
【发布时间】:2017-01-25 16:40:56
【问题描述】:

我有动态 JSON,这里是示例:http://pastebin.com/QMWRZTrD

我如何用 Retrofit 解析它?

我未能生成 POJO 类,因为我有像“5411”和“5412”这样的动态字段。

编辑

我使用 Map 解决了这个问题,因为第一个值总是整数,第二个是对象列表。

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

【问题讨论】:

  • 您可以使用Map 代替 POJO。
  • 发布答案,因为我是按照你的想法解决的。

标签: android json retrofit2


【解决方案1】:

如果是随机键,您可以使用Map 对其进行序列化和反序列化。 Observable&lt;Map&lt;Integer, List&lt;YourObject&gt;&gt;&gt;

【讨论】:

    【解决方案2】:

    您可以在 RestApi 接口中获取改造 api 调用以返回字符串,例如

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

    为此,您需要将标量转换器工厂添加到您创建 Retrofit 对象的位置。 首先你需要导入它:

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

    然后添加:

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

    然后在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 {
    
        }
    }
    

    另外,请查看this site,它有很棒的改造教程。

    【讨论】:

    • Hvala Dusane,悲伤的 cu probati :)
    • Rijesio sam na osnovu mape、iako je ovaj tvoj nacin zanimjiv、nisam znao da moze ovako。波兹德拉夫我哈瓦拉!
    • Nema na cemu, ja sam mislio da nece moci da deserijalizuje automatski pa sam ti zato rekao da treba da vrati String pa onda da ga deserijalizujes ,ali dobro ako radi automatski :)
    猜你喜欢
    • 2016-01-09
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2018-05-31
    • 2018-05-24
    相关资源
    最近更新 更多