如何使用改进2.3.0解析json对象

时间:2018-05-05 20:15:36

标签: java android json retrofit2

我们的团队决定使用Retrofit2,我正在对这个库进行一些初步研究,但我是Retrofit的新手。如何解析下面的Json?

    {
    "main": {
    "totalResults": "500",
    "libelleCategory": "Véhilcule",
    "libelleSubCategory": "Mots et Vélos",
    "idCategory": "1",
    "idSubCategory": "3",
    "row": [
       {
            "id": "66888",
            "shortURL": "https://www.testimage.com",
            "title": "Moto - HONDA - 2007",
            "text": "Pan lorem ipsum test test c'est un test",
            "img": "https://www.test.image.com",
           "price": "6 200",
           "datePublish": "05/05/2018",
           "nbPhotos": "3",
           "address": "75001 Paris"
       },
       {
           "id": "66889",
           "shortURL": "https://www.testimage.com",
           "title": "Moto  - 2018",
           "text": "Pan lorem ipsum test test c'est un test",
           "img": "https://www.test.image.com",
           "price": "9 500",
           "datePublish": "05/05/2018",
           "nbPhotos": "5",
           "address": "75001 Paris"
       }
     ]
  }
}

提前致谢

1 个答案:

答案 0 :(得分:0)

初始化API时,您必须添加JSON转换器。

我最喜欢的是杰克逊:

  1. 添加依赖项:com.squareup.retrofit:converter-jackson

  2. 设置转换器以进行改造

    Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://your.domain")
    .addConverterFactory(JacksonConverterFactory.create()) // In real app, you should provide a preconfigured ObjectMapper for better performance
    .build();
    
  3. 修改

    示例:

    创建与JSON匹配的模型:

    public class YourResponse {
        private Detail main; // This will match "main": {}
    
        public static final class Detail {
           private String totalResults; // This will match "totalResults": ...
           private String libelleCategory;
           private String libelleSubCategory;
           ... bla bla....
           ... your getter/setter method....
        }
        ... your getter/setter method....
    }
    

    在API类中使用它:

    public interface SampleApi {
    
      @Get("/your/path/to/get")
      Call<YourResponse> getResponse();
    }
    

    初始化您的API:

    SampleApi api = new Retrofit.Builder()
                        .baseUrl("https://your.domain")
                        .addConverterFactory(JacksonConverterFactory.create()) // In real app, you should provide a preconfigured ObjectMapper for better performance
                        .build()
                        .create(SampleApi.class);
    

    致电您的API:

    Response<YourResponse> serverResponse = api.getResponse().execute();
    if (serverResponse.isSuccessful()) {
      YourResponse = serverResponse.body();
    }