如何在android中使用批注解析动态json和retrofit 2 [英] How to parse dynamic json in android with retrofit 2 using annotations

查看:126
本文介绍了如何在android中使用批注解析动态json和retrofit 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON结构,我想用retrofit 2(@Expose)解析。下面我提到了JSON。

  {
状态:1,
消息需要帮助来解析它使用动态注释。 :成功,
data:[
{
type:1,
heading:,
description: ,
created_on:141123213,
author_id:123,
author_name:某个名字,
author_pic:some_pic,
read_time:3.1分钟,
post_pic_url:,
post_web_url:,
isLiked:false,
isSaved: false,
totalLikes:12
},
{
type:2,
author_id:123,
author_name: some name,
author_pic:一些图片,
author_about:,
tags:[
travel,weekends
],
isFollowing:false
},
{
type:3,
poll_name:某个名字,
poll_options:[
opt1,opt2,opt3
],
author_id:123,
author_name:某个名字,
author_pic:一些图片,
isLiked:true,
isFollowing:假
},
{
type:4,
ad_url:url,
ad_pic:pic
} ,
{
type:5,
tags:[
tag1,tag2,tag3
]
}
]
}

我已经更新了所有5种类型的JSON结构。

解决方案

1使用Retrofit转换
例如GSON转换

2在gradle文件中添加com.squareup.retrofit2:converter-gson
3在Retrofit对象中添加转换器工厂



Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Ws_Url)
.addConverterFactory(GsonConverterFactory.create())
.client(clientBuilder.build())
.build();



4为您的回复创建模型类
使用下面的链接生成模型类
http://www.jsonschema2pojo.org/

I have a JSON structure which I want to parse using retrofit 2 (@Expose). Below I have mentioned the JSON. Need help to parse it using dynamic annotations.

{
  "status": 1,
  "message": "success",
  "data" : [
    {
      "type": 1,
      "heading": "",
      "description": "",
      "created_on": 141123213,
      "author_id": 123,
      "author_name": "some name",
      "author_pic": "some_pic",
      "read_time": "3.1 min",
      "post_pic_url": "",
      "post_web_url": "",
      "isLiked": false,
      "isSaved": false,
      "totalLikes": 12
   },
   {
      "type": 2,
      "author_id": 123,
      "author_name": "some name",
      "author_pic": "some pic",
      "author_about": "",
      "tags":[
        "travel", "weekends"
      ],
      "isFollowing": false
   },
   {
     "type": 3,
     "poll_name": "Some name",
     "poll_options": [
       "opt1", "opt2", "opt3"
     ],
     "author_id": 123,
     "author_name": "some name",
     "author_pic": "some pic",
     "isLiked": true,
     "isFollowing": false
   },
   {
     "type": 4,
     "ad_url": "url",
     "ad_pic": "pic"
   },
   {
     "type": 5,
     "tags": [
       "tag1", "tag2", "tag3"
     ]
   }
  ]
 }

I have updated the JSON structure with all 5 types.

解决方案

1 Use Retrofit convert example GSON convert

2 Add com.squareup.retrofit2:converter-gson in gradle file 3 Add converter factory in Retrofit object

Retrofit retrofit = new Retrofit.Builder() .baseUrl(Ws_Url) .addConverterFactory(GsonConverterFactory.create()) .client(clientBuilder.build()) .build();

4 Create Model class for Your response Use below link to generate model class http://www.jsonschema2pojo.org/

这篇关于如何在android中使用批注解析动态json和retrofit 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆