01-Android 序列化与反序列化

news2024/10/6 18:24:22

1. 背景

在日常开发过程中,经常遇到程序读取文件,将文件数据转换为对象,程序通过对象传输数据,或者通过对象读取数据。同时也会经常遇到对象数据写入文件操作。

如果采用常规的文件读写,然后再进行赋值;那么将耗费很多时间码代码实现,同时,如果在文件参数较多的情况下,采用常规操作将是一个重大工程量。囧o(╯□╰)o

那么软件前辈经过日夜奋进,不断创新,总结开发出很多优秀的反序列化及序列化工具/sdk/库,如下图所示

通过序列化&反序列化sdk,大大提高软件操作文件效率。

2. 方案

2.1 json

推荐方案:阿里的 fastjson

2.1.1 fastjson

Fastjson 是一个 Java 库,可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象。Fastjson 可以操作任何 Java 对象,即使是一些预先存在的没有源码的对象。

Android使用要点:

  • gradle导入

    implementation 'com.alibaba:fastjson:1.1.71.android'

  • 反序列化:

 > > 示例json:

{
  "id":"12345678",
  "version":"202311111",
  "code":"100001",
  "data":[
    {
      "name": "MSG_P1",
      "value":"610000",
      "count":1,
      "accuracy":1
    },
    {
      "name": "MSG_P2",
      "value":"5 15 25 35 45 55 65 75 85 95 105 115 125 135 145 155 165 175 185 195 205 215 225 235",
      "count":24,
      "accuracy":10
    }
  ]
}

 > > 创建对象

package com.auto.utils
import com.alibaba.fastjson.annotation.JSONType;

import java.util.ArrayList;
import java.util.List;

@JSONType(orders={"id","version","code","data"}) //序列化、反序列化顺序
public class JsonMsg {
    private String id;
    private String version;
    private String code;
    private List<JsonData> data= new ArrayList<>();

    public void setId(String id) {
        this.id= id;
    }

    public void setVersion(String version) {
        this.version= version;
    }

    public void setCode(String code) {
        this.code= code;
    }

    public void setJsonData(List<JsonData> data) {
        this.data= data;
    }

    public String getId() {
        return id;
    }

    public String getVersion() {
        return version;
    }

    public String getCode() {
        return code;
    }

    public List<JsonData> getJsonData() {
        return data;
    }
}
package com.auto.utils;

import com.alibaba.fastjson.annotation.JSONType;

@JSONType(orders={"name","value","count","accuracy"})//序列化、反序列化顺序
public class JsonData {
    private String name;
    private String value;
    private int count;
    private int accuracy;

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setAccuracy(int accuracy) {
        this.accuracy = accuracy;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public int getCount() {
        return count;
    }

    public int getAccuracy() {
        return accuracy;
    }
}

 > > 接口: JSON.parseObject

方法原型:

public static final <T> T parseObject(String text, Class<T> clazz) {
    return parseObject(text, clazz, new Feature[0]);
}

 > > 使用://伪代码

private JsonMsg jsonMsg;

...

try {
    String json_str = loadJSONFromAsset(mContext,"test");
    JSONObject jsonObject = JSON.parseObject(json_str, Feature.OrderedField);//
    if(jsonObject instanceof JSONObject) {
        jsonMsg = JSON.parseObject(jsonObject.toJSONString(),JsonMsg .class);
    }else{
        Log.e(TAG,"jsonObject is not JSONObject.");
    }

}catch (Exception e){
    e.printStackTrace();
}

/**
* load json file from assset.
* @param context
* @param fileName
* @return
*/
public static synchronized String loadJSONFromAsset(Context context,String fileName) {
	String json = null;
	try {
		InputStream is = context.getAssets().open(fileName + ".json");
		int size = is.available();
		byte[] buffer = new byte[size];
		is.read(buffer);
		is.close();
		json = new String(buffer, "UTF-8");
	} catch (IOException ex) {
		ex.printStackTrace();
		return null;
	}
	return json;
}

  • 序列化

 >> 接口  JSON.toJSONString

方法原型:

public static final String toJSONString(Object object) {
	return toJSONString(object, SerializeConfig.globalInstance, null, null, DEFAULT_GENERATE_FEATURE);
}

/**
 * @since 1.2.11
 */
public static final String toJSONString(Object object, SerializerFeature... features) {
	return toJSONString(object, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONString(Object object, int defaultFeatures, SerializerFeature... features) {
	return toJSONString(object, SerializeConfig.globalInstance, null, null, defaultFeatures, features);
}

/**
 * @since 1.1.14
 */
public static final String toJSONStringWithDateFormat(Object object, String dateFormat,
													  SerializerFeature... features) {
	return toJSONString(object, SerializeConfig.globalInstance, null, dateFormat, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONString(Object object, SerializeFilter filter, SerializerFeature... features) {
	return toJSONString(object, SerializeConfig.globalInstance, new SerializeFilter[] {filter}, null, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONString(Object object, SerializeFilter[] filters, SerializerFeature... features) {
	return toJSONString(object, SerializeConfig.globalInstance, filters, null, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONString(Object object, SerializeConfig config, SerializerFeature... features) {
	return toJSONString(object, config, null, null, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONString(Object object, SerializeConfig config, SerializeFilter filter,
										SerializerFeature... features) {
	return toJSONString(object, config, new SerializeFilter[] {filter}, null, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONString(Object object, SerializeConfig config, SerializeFilter[] filters,
										SerializerFeature... features) {
	return toJSONString(object, config, filters, null, DEFAULT_GENERATE_FEATURE, features);
}

public static final String toJSONStringZ(Object object, SerializeConfig mapping, SerializerFeature... features) {
	return toJSONString(object, SerializeConfig.globalInstance, null, null, 0, features);
}

> >  使用:

/**
 * //先执行static代码块,再执行该方法
 * //是否输出值为null的字段,默认为false
 * JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteMapNullValue.getMask();
 * //数值字段如果为null,输出为0,而非null
 * JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteNullNumberAsZero.getMask();
 * //List字段如果为null,输出为[],而非null
 * JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteNullListAsEmpty.getMask();
 * //字符类型字段如果为null,输出为 "",而非null
 * JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteNullStringAsEmpty.getMask()
 */
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteMapNullValue.mask;
Log.e(TAG,"class -> json:" + JSON.toJSONString(jsonMsg));//jsonMsg 在反序列化中有定义
saveJSONtoStorage(FilesUtils.getJsonFile(),JSON.toJSONString(jsonMsg));


/**
 * saveJSONtoStorage
 * @param filePath
 * @param jsonString
 * @return
 */
public static synchronized void saveJSONtoStorage(String filePath,String jsonString) {
	String json = null;
	//TODO
	try {
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		} else {
			return;
		}
	}catch (Exception e){
		e.printStackTrace();
		return;
	}

	try {
		if(filePath == null){
			Log.e(TAG,"saveJSONtoStorage filePath is null");
			return;
		}
		File file = new File(filePath);
		FileWriter fw = null;
		if (file.exists()) {
			fw = new FileWriter(file, true);
		} else {
			fw = new FileWriter(file, false);
		}
		fw.write(String.format("%s", jsonString));
		fw.write(13);
		fw.write(10);
		fw.flush();
		fw.close();
	} catch (Throwable ex) {
		ex.printStackTrace();
	}
}

 

2.1.2 jackson

 //TODO

2.2 xml

推荐方案:jackson-dataformat-xml

Android使用步骤:

  • gradle导入:
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.14.2'
    implementation 'javax.xml.stream:stax-api:1.0-2'
  • xml文件示例:
<?xml version="1.0" encoding="utf-8"?>
<XmlMsg>
	<id>12345678</vehicleID>
	<vcuVersion>202311111</vcuVersion>
	<checkCode>100001</checkCode>
	<xmlDataList>
		<xmlData>
			<name>MSG_P1</name>
			<value>610000</value>
			<count>1</count>
			<accuracy>1</accuracy>
		</xmlData>

		<xmlData>
			<name>MSG_P2</name>
			<value>5 15 25 35 45 55 65 75 85 95 105 115 125 135 145 155 165 175 185 195 205 215 225 235</value>
			<count>24</count>
			<accuracy>10</accuracy>
		</xmlData>
	</xmlDataList>
</XmlMsg>
  •  创建对象
package com.auto.utils
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

import java.util.ArrayList;
import java.util.List;

@JacksonXmlRootElement(localName = "XmlMsg")
@JsonPropertyOrder({"id","version","code","data"}) //序列化、反序列化顺序
public class XmlMsg {
    @JacksonXmlProperty(localName = "id")
    private String id;
    @JacksonXmlProperty(localName = "version")
    private String version;
    @JacksonXmlProperty(localName = "code")
    private String code;
    @JacksonXmlElementWrapper(localName = "xmlDataList")
    @JacksonXmlProperty(localName = "xmlData")
    private List<xmlData> data= new ArrayList<>();

    public void setId(String id) {
        this.id= id;
    }

    public void setVersion(String version) {
        this.version= version;
    }

    public void setCode(String code) {
        this.code= code;
    }

    public void setJsonData(List<JsonData> data) {
        this.data= data;
    }

    public String getId() {
        return id;
    }

    public String getVersion() {
        return version;
    }

    public String getCode() {
        return code;
    }

    public List<JsonData> getJsonData() {
        return data;
    }
}
package com.auto.utils;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

@JsonPropertyOrder({"name", "value", "count","accuracy"})//序列化、反序列化顺序
public class JsonData {
    @JacksonXmlProperty(localName = "name")
    private String name;
    @JacksonXmlProperty(localName = "value")
    private String value;
    @JacksonXmlProperty(localName = "count")
    private int count;
    @JacksonXmlProperty(localName = "accuracy")
    private int accuracy;

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setAccuracy(int accuracy) {
        this.accuracy = accuracy;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public int getCount() {
        return count;
    }

    public int getAccuracy() {
        return accuracy;
    }
}
  • 序列化&反序列化
try {
	//XNL反序列化为对象
	AssetManager am = context.getResources().getAssets();
	InputStream in = am.open( "test" + ".xml");
	ObjectMapper xmlMapper = XmlMapper.builder(new XmlFactory(new WstxInputFactory(), new WstxOutputFactory())).build();
	XmlMsg xmlMsg = xmlMapper.readValue(in,XmlMsg .class);


	//对象序列化为XML
	xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
	xmlMapper.writeValue(new File(FilesUtils.getXmlFile()), xmlMsg );

}catch (Exception e){
	e.printStackTrace();
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/420455.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

每日学术速递4.16

CV - 计算机视觉 | ML - 机器学习 | RL - 强化学习 | NLP 自然语言处理 Subjects: cs.CV 1.SpectFormer: Frequency and Attention is what you need in a Vision Transformer 标题&#xff1a;SpectFormer&#xff1a;频率和注意力是您在 Vision Transformer 中所需要的 …

医院不良事件报告系统源码:基于PHP+vue2+element+laravel8技术开发

医院不良事件报告系统源码 文末获取联系&#xff01; 技术架构&#xff1a;前后端分离&#xff0c;仓储模式&#xff0c; 开发语言&#xff1a;PHP 开发工具&#xff1a;vscode 前端框架&#xff1a;vue2element 后端框架&#xff1a;laravel8 数 据 库&#xff1a;mysql5…

一文读懂Java类加载全过程,面试必备!

1、概述 Java类加载过程是Java虚拟机&#xff08;JVM&#xff09;将.class文件中的字节码装载到内存中&#xff0c;并对字节码进行验证、准备和初始化的过程。这个过程涉及到了Java虚拟机的类加载器、运行时数据区等多个方面&#xff0c;其中包含了很多的细节和技术问题。 类加…

前端开发神器bootstrap介绍

想必刚开始学习前端的小伙伴在为设计优美的前端页面很苦恼吧&#xff0c;心中有好的比较不错的UI样式却无法绘制出来&#xff0c;学习呢又可能会有点困难&#xff0c;其实前端是很容易并不难学的&#xff0c;在前端设计上也有很多的开源库的&#xff0c;这些第三方的开源库已经…

12、视图解析器与模板引擎

文章目录1、视图解析1.1 spring boot支持的第三方模板引擎技术1.2、视图解析原理流程2、模板引擎-Thymeleaf2.1、thymeleaf简介2.2、基本语法1、表达式2、字面量3、文本操作4、数学运算5、布尔运算6、比较运算7、条件运算8、特殊操作2.3、设置属性值-th:attr2.4、迭代2.5、条件…

【数据结构】顺序表(上)

所属专栏&#xff1a;初始数据结构 博主首页&#xff1a;初阳785 代码托管&#xff1a;chuyang785> 感谢大家的支持&#xff0c;您的点赞和关注是对我最大的支持&#xff01;&#xff01;&#xff01; 博主也会更加的努力&#xff0c;创作出更优质的博文&#xff01;&#x…

(十六)排序算法-桶排序

1 基本介绍 1.1 概述 桶排序 &#xff08;Bucket sort&#xff09;或所谓的箱排序&#xff0c;是一个排序算法&#xff0c;工作的原理是将数组分到有限数量的桶里。每个桶再个别排序&#xff08;有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序&#xff09;&a…

ZYNQ:【1】深入理解PS端的TTC定时器(Part1:原理+官方案例讲解)

碎碎念&#xff1a;好久不见&#xff0c;甚是想念&#xff01;本期带来的是有关ZYNQ7020的内容&#xff0c;我们知道ZYNQ作为一款具有硬核的SOC&#xff0c;PS端很强大&#xff0c;可以更加便捷地实现一些算法验证。本文具体讲解一下里面的TTC定时器&#xff0c;之后发布的Part…

Java-初识 .class 文件

一、概述 class文件全名称为 Java class 文件&#xff0c;主要在平台无关性和网络移动性方面使 Java 更适合网络。该文件打破了 C 或者 C 等语言所遵循的传统&#xff0c;使用这些传统语言写的程序通常首先被编译&#xff0c;然后被连接成单独的、专门支持特定硬件平台和操作系…

面试被问到vue的diff算法原理,我不允许你回答不上来

一、是什么 diff 算法是一种通过同层的树节点进行比较的高效算法 其有两个特点&#xff1a; 比较只会在同层级进行, 不会跨层级比较在diff比较的过程中&#xff0c;循环从两边向中间比较 diff 算法在很多场景下都有应用&#xff0c;在 vue 中&#xff0c;作用于虚拟 dom 渲…

nvm实现多版本node自由切换

nvm&#xff0c;全称是node.js version management,可以在多个node版本之间自由切换&#xff01; 1、下载文件 github Releases coreybutler/nvm-windows GitHub 2、安装nvm 注意&#xff1a;安装前必须完全卸载node 彻底从Windows中删除Node.js 1、从卸载程序卸载程序和功…

【性能测试】Jemeter+mysql+CSV+InfluxDB+Granafa数据库性能测试及监控

Jmeter连接Mysql并执行事务 一、下载驱动并加入jmeter 1.mysql驱动下载地址&#xff1a;MySQL :: Download MySQL Connector/J (Archived Versions) 找到对应的驱动下载(版本一定要对应) 2.下载后&#xff0c;解压&#xff0c;找到驱动jar包复制到桌面&#xff1a; 3.把驱动j…

CODOSYS之结构化文本(ST)——中级篇(一)计时器的应用

标准库中常用的计时器有如下四个&#xff08;部分环境还支持高精度计时器如LTON等等&#xff09;&#xff1a; .RTC .TON .TOF .TP 本文将对将对上述四个计时器进行简单的讲解。 .RTC&#xff1a; RunTime 时钟定时器&#xff0c;返回启动时间&#xff0c;当前时间和日…

别搞了 软件测试真卷不动了...

内卷可以说是 2022年最火的一个词了。2023 年刚开始&#xff0c;在很多网站看到很多 软件测试的 2022 年度总结都是&#xff1a;软件测试 越来越卷了&#xff08;手动狗头&#xff09;&#xff0c;2022 年是被卷的一年。前有几百万毕业生虎视眈眈&#xff0c;后有在职人员带头“…

L2-042 老板的作息表(极短代码)

题目&#xff1a; 新浪微博上有人发了某老板的作息时间表&#xff0c;表示其每天 4:30 就起床了。但立刻有眼尖的网友问&#xff1a;这时间表不完整啊&#xff0c;早上九点到下午一点干啥了&#xff1f; 本题就请你编写程序&#xff0c;检查任意一张时间表&#xff0c;找出其中…

企业推广常用的网络推广方法有哪些?

网络推广是指通过互联网向目标用户推广产品、服务或品牌的过程&#xff0c;其主要目的是为了扩大业务范围&#xff0c;提高企业知名度&#xff0c;增加销售额。在当今的数字化时代&#xff0c;网络推广已经成为了企业不可或缺的一部分。本文将介绍一些常见的网络推广方法和途径…

Linux安装中文字体

前言 Lunix默认没有中文字库&#xff0c;很容易导致项目开发时出现中文字符乱码的情况。 1 查看linux已安装字体 fc-list如出现-bash: fc-list: command not found 说明Linux中没有安装字体库&#xff0c;需要先安装字体库 2 Linux安装字体 yum -y install fontconfig执行…

不平衡电网电压下虚拟同步发电机VSG控制策略-实现不平衡电压下控制三相电流平衡

资源地址&#xff1a; 不平衡电网电压下虚拟同步发电机VSG控制策略-实现不平衡电压下控制三相电流平衡-电子商务文档类资源-CSDN文库 主体模型&#xff1a; VSG控制&#xff1b;正负序分离&#xff1b;正负序控制&#xff1b;电压电流双环控制&#xff01;&#xff01;&…

[LCA]最近公共祖先(倍增)

概念引入 祖先 祖先其实很好理解&#xff0c;一个节点的 **父节点 以及 父节点的父节点 以及 父节点的父节点的父……**都是这个节点的祖先 比如说上面的 ddd 节点&#xff0c; bbb 节点和 aaa 节点都是它的祖先 kkk 级祖先 称节点 &#x1d465; 的父节点为 &#x1d465; …

带你走进Flutter 3.7

期待已久的新教程上线啦&#xff01;解锁Flutter开发新姿势&#xff0c;一网打尽Flutter最新与最热技术&#xff0c;点我Get!!! 新年伊始&#xff0c;由 Flutter 3.7 正式版来「打头阵」&#xff01;我们与整个 Flutter 社区们继续在 Flutter 3.7 中优化了框架&#xff0c;包括…