【问题标题】:Parsing nested json objects in retrofit android在改造android中解析嵌套的json对象
【发布时间】:2018-09-23 09:16:24
【问题描述】:

我无法在改造中解析 json,这是我的示例 json,键是动态的,这样的 json 数据需要什么 POJO 定义:

    {
    "Fri Mar 23 2018 17:35:36 GMT+0530 (IST)": {
        "PDF": "",
        "URL": "",
        "image": "",
        "shortDescription": "test one",
        "timestamp": "2018-03-23T12:05:36.319Z",
        "title": "test "
    },
    "Fri Mar 23 2018 17:44:43 GMT+0530 (IST)": {
        "PDF": "",
        "URL": "",
        "image": "",
        "shortDescription": "two test",
        "timestamp": "2018-03-23T12:14:43.194Z",
        "title": "two"
    },
    "Fri Mar 23 2018 17:49:06 GMT+0530 (IST)": {
        "PDF": "",
        "URL": "https://twitter.com/CodingDoug/status/942576182276497409",
        "image": "https://drive.google.com/open?id=1gBUaAVdAttmAqv68OChHCDqlbKAoxZW6",
        "shortDescription": "test three",
        "timestamp": "2018-03-23T12:19:06.835Z",
        "title": "three"
    },
    "Mon Mar 26 2018 15:56:06 GMT+0530 (IST)": {
        "PDF": "",
        "URL": "https://www.goodmorningquote.com/inspirational-monday-quotes-start-happy/",
        "image": "https://drive.google.com/open?id=1fg1z0_jzTUUiXhvkHyGLewJC2LFFzEyW",
        "shortDescription": "1st day of week, great day to plan and jumpstart week ",
        "timestamp": "2018-03-26T10:26:06.983Z",
        "title": "Monday test 1 "
    }
}

【问题讨论】:

标签: android json retrofit


【解决方案1】:

尝试Map<String, Object> 解析json。 String 是这里的变量键。 对象是您的“PDF”、“URL”的 POJO, “图片”, “简短的介绍”, “时间戳”, “标题”:“测试”

【讨论】:

    【解决方案2】:

    您可以创建如下类用于 json 解析:

    Gson gson = GsonBuilder().enableComplexMapKeySerialization().serializeNulls().setPrettyPrinting().create();
    
            List<ModelClass> dataList= new ArrayList<>();
            JSONObject issueObj = new JSONObject(jsonContent);
              Iterator iterator = issueObj.keys();
               while(iterator.hasNext()){
                String key = (String)iterator.next();
                JSONObject issue = issueObj.getJSONObject(key);
    
    
            ModelClass model = gson.fromJson(issue.toString(), ModelClass.class);
    
        dataList.add(model);
                }
    

    你的模型类将是:

    import java.io.Serializable;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class ModelClass implements Serializable
    {
    
    @SerializedName("PDF")
    @Expose
    private String pDF;
    @SerializedName("URL")
    @Expose
    private String uRL;
    @SerializedName("image")
    @Expose
    private String image;
    @SerializedName("shortDescription")
    @Expose
    private String shortDescription;
    @SerializedName("timestamp")
    @Expose
    private String timestamp;
    @SerializedName("title")
    @Expose
    private String title;
    
    
    public String getPDF() {
    return pDF;
    }
    
    public void setPDF(String pDF) {
    this.pDF = pDF;
    }
    
    public String getURL() {
    return uRL;
    }
    
    public void setURL(String uRL) {
    this.uRL = uRL;
    }
    
    public String getImage() {
    return image;
    }
    
    public void setImage(String image) {
    this.image = image;
    }
    
    public String getShortDescription() {
    return shortDescription;
    }
    
    public void setShortDescription(String shortDescription) {
    this.shortDescription = shortDescription;
    }
    
    public String getTimestamp() {
    return timestamp;
    }
    
    public void setTimestamp(String timestamp) {
    this.timestamp = timestamp;
    }
    
    public String getTitle() {
    return title;
    }
    
    public void setTitle(String title) {
    this.title = title;
    }
    
    }
    

    【讨论】:

    • 老兄,键是动态的。
    【解决方案3】:

    当您获取 json 数据时,制作改造对象并制作 pojo 类 如果要生成 pojo 类,请参考此站点.. http://www.jsonschema2pojo.org/

    把你的 json 数据放到它提供的所有 pojo 类..

    然后制作如下改造对象.. 使 Apiclient 类像

    public class ApiClient {
    private final static String BASE_URL = "https://simplifiedcoding.net/demos/";
    public static ApiClient apiClient;
    private Retrofit retrofit = null;
    
    public static ApiClient getInstance() {
        if (apiClient == null) {
            apiClient = new ApiClient();
        }
        return apiClient;
    }
    
    //private static Retrofit storeRetrofit = null;
    
    public Retrofit getClient() {
        return getClient(null);
    }
    
    private Retrofit getClient(final Context context) {
    
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.readTimeout(60, TimeUnit.SECONDS);
        client.writeTimeout(60, TimeUnit.SECONDS);
        client.connectTimeout(60, TimeUnit.SECONDS);
        client.addInterceptor(interceptor);
        client.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
    
                return chain.proceed(request);
            }
        });
    
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client.build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
    
        return retrofit;
    }
    }
    

    然后为api调用制作接口,如下所示

    public interface ApiInterface {
    @GET("marvel/")
    Call<List<Hero>> getHero(); // here pass your response pojo class name.
    }
    

    在主要活动中如何调用如下..

     ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    
    Call<List<Hero>> call = apiInterface.getHero();
    
        call.enqueue(new Callback<List<Hero>>() {
        @Override
        public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
        }
    
        @Override
        public void onFailure(Call<List<Hero>> call, Throwable t) {
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多