iOS转android之json反序列化

在《iOS转android之网络封装》https://www.jianshu.com/p/5159b214b361中提到了json数据解析,这是网络封装中非常重要的一部分,如果没有一个好的框架简单快捷的将从服务器获取的json数据处理成我们需要的model,那么我们甚至需要手动转换,一个个的将json中的数据赋值给model对象,这无疑非常浪费时间。

iOS-OC之MJExtension

这里简单介绍几种使用场景

  1. MJExtension处理服务器返回的key值和model中的key值不对应,使用mj_replacedKeyFromPropertyName
+ (NSDictionary *)mj_replacedKeyFromPropertyName
{
    return @{@"ID":@"id"}; //本地ID,服务器返回id
}
  1. MJExtension处理model中有对象,不需要特殊处理,直接使用
#import <Foundation/Foundation.h>
#import <MJExtension/MJExtension.h>
#import "Student.h"

@interface Person : NSObject

@property (nonatomic, strong) NSString *birthday;
@property (nonatomic, strong) Student *stu;

@end
  1. MJExtension处理model中有对象数组使用mj_objectClassInArray
+ (NSDictionary *)mj_objectClassInArray
{
    return @{@"vip":@"TMDiscoverVIPListModel", @"topic":@"TMDiscoverTopicListModel"};
}

model中vip数组中存储的是TMDiscoverVIPListModel对象,topic数组存储的是TMDiscoverTopicListModel数组

  1. MJExtension数据格式处理,例如服务器返回时间戳我们需要YYYY-MM-dd
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property{
    if ([property.name isEqualToString:@"birthday"]) {
        if (oldValue) {
            // 格式化时间
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
            [formatter setDateStyle:NSDateFormatterMediumStyle];
            [formatter setTimeStyle:NSDateFormatterShortStyle];
            [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
            NSDate* date = [NSDate dateWithTimeIntervalSince1970:[oldValue doubleValue]];
            NSString* dateString = [formatter stringFromDate:date];
            return dateString;
            }
        }
        else {
            return @"日期有误";
        }
    return oldValue;
}

iOS-swift之HandyJSON

HandyJSON是阿里巴巴推出的一个好用的工具,使用方法也很简单,model类继承自HandyJSON并且实现required init(){}方法

class model: HandyJSON {
    required init(){} //必须要实现
}
  1. HandyJSON处理服务器返回的key值和model中的key值不对应,使用mapping方法
class model: HandyJSON {
    var ID:String = "" /** 服务器返回id*/

    required init(){} //必须要实现

    //将系统返回的id和本地ID关联起来
    func mapping(mapper: HelpingMapper) {
        mapper <<<
            self.ID <-- "id"
    }
}
  1. HandyJSON处理model中有对象,不需要特殊处理,直接使用
class model: HandyJSON {
    var subclass: SubClass?
    required init(){} //必须要实现

   class SubClass: HandyJSON{
        var name:String = ""
         required init(){} //必须要实现
    }
}
  1. HandyJSON处理model中有对象数组
class model: HandyJSON {
    var subClassArr:Array<SubClass>?
    required init(){} //必须要实现

   class SubClass: HandyJSON{
        var name:String = ""
        required init(){} //必须要实现
    }
}
  1. HandyJSON数据格式处理,例如服务器返回时间戳我们需要YYYY-MM-dd
class model: HandyJSON {
    var data: Data?

    required init(){} //必须要实现

    //时间格式化
    func mapping(mapper: HelpingMapper) {
        mapper <<<
            date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
    }
}

如果只需要简单解析json而不用转化为model那么推荐另一个好用的工具
SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON

Android之Gson

Android中解析json数据比较常用的有Gson和FastJson,我接触Android开发以后解析json数据就是使用Gson,没有使用过FastJson就不多做介绍。

Gson配合网络请求的几种使用场景

  1. Gson处理服务器返回的key值和model中的key值不对应,使用SerializedName注解
        /**
         * list中的数据
         */
        public static class ListData{
            //有用的字段
            @SerializedName("id")
            private String notifyId  =  ""; /** 服务器返回id、notifyId*/

            public String getNotifyId() {
                return notifyId;
            }

        }

如果不同接口可能返回idIDnid那么怎么处理呢

        /**
         * list中的数据
         */
        public static class ListData{
            //有用的字段
            @SerializedName(value = "id", alternate = {"ID", "nid"})
            private String notifyId  =  ""; /** 服务器可能返回id、ID、nid、notifyId*/

            public String getNotifyId() {
                return notifyId;
            }

        }

⚠️需要注意的是虽然我们使用了注解SerializedName,但是如果服务器返回notifyId仍然是可以接收的

  1. Gson处理model中有对象,不需要特殊处理,直接使用
public class MessageListDao {

    private DataBean data = new DataBean();
    public DataBean getData() {
        return data;
    }

    /**
     * data中的数据
     */
    public static class DataBean{

    }
}
  1. Gson处理model中有对象数组
public class MessageListDao {

    private DataBean data = new DataBean();
    public DataBean getData() {
        return data;
    }

    /**
     * data中的数据
     */
    public static class DataBean{
        private ArrayList<ListData> list = new ArrayList<>();
        public ArrayList<ListData> getList() {
            return list;
        }

        /**
         * list中的数据
         */
        public static class ListData{
            private String notifyId  =  ""; 
            public String getNotifyId() {
                return notifyId;
            }
        }
    }

}
  1. Gson数据格式处理,例如服务器返回时间戳我们需要YYYY-MM-dd

创建Gson对象有两种方法

        //通过构造函数来获取
        Gson gson = new Gson();
        //通过 GsonBuilder 来获取,可以进行多项特殊配置
        Gson gson = new GsonBuilder().create();

可以使用builder来创建Gson对象并配置相关属性

Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();

通过builder生成Gson对象时可以选择的配置非常丰富参考
Gson https://github.com/google/gson

⚠️需要注意的是服务器有时候返回的json格式很随意很奔放我们无法控制,那么在解析json数据时一定要加上

        try {
            t = (T)gson.fromJson(entity,tClass);
        }catch (Exception e){
            Log.e("解析错误",e.toString());
        }

任何成熟的框架都不是几句话就能说清楚的,这里就是简单介绍满足入门选手达到会用的程度,抛砖引玉共同提高

参考
MJExtension https://www.jianshu.com/p/1efa3c2ffde3
HandyJSON https://github.com/alibaba/HandyJSON
SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON
Gson https://www.jianshu.com/p/0444693c2639
Gson https://github.com/google/gson

猜你喜欢

转载自blog.csdn.net/weixin_34279061/article/details/87429284