HarmonyOS鸿蒙Next中实现Gson集成示例代码
HarmonyOS鸿蒙Next中实现Gson集成示例代码
介绍
鸿蒙ets侧想使用map,保存打点上报的数据,但是Map和HashMap都不支持序列化,使用起来不方便。Gson用于对象与JSON字符串之间的互相转换,并支持JsonElement对象类型,功能比系统的HashMap能力会丰富一些,能满足绝大部分JSON数据的处理场景。由于该库未入OHPM仓库,需要手动下载源代码集成。
注:三方库Gson官方已停止维护,建议使用JSON。
使用说明
以har包的方式集成到HamronyOS工程:
- 拷贝ohos_gson/library目录到工程根目录,并修改文件夹名称为gson
- 修改gson/hvigorfile.js内容:
import { harTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
- 修改工程根目录build-profile.json5文件,添加如下内容:
"modules": [
...
{
"name": "gson",
"srcPath": "./gson"
}
...
]
- 在需要依赖的模块中添加依赖,比如entry模块依赖gson,则在entry/oh-package.json5文件dependencies字段中添加如下内容:
{
...
"dependencies": {
"gson": "file:../gson"
},
...
}
实现思路
- JsonObject序列化
let jsonObj: JsonObject = new JsonObject()
jsonObj.addProperty('code', 400)
jsonObj.addProperty('message', '参数错误')
let gsonObj = new Gson().toJson(jsonObj)
this.message = gsonObj.toString()
console.info(`Demo JsonObj序列化: jsonStr:${gsonObj.toString()}`)
- 反序列化JsonObject
let str = '{"code":400,"message":"参数错误"}'
let jsonObj: JsonObject = parseString(str) as JsonObject
let code = jsonObj.getAsJsonPrimitiveByMemberName('code')
let message = jsonObj.getAsJsonPrimitiveByMemberName('message')
console.info(`Demo ${this.message}`)
- JsonArray序列化
let jsonArray = new JsonArray()
let emptyArray = new JsonArray()
let str = '{"code":400,"message":"参数错误"}'
let jsonObj: JsonObject = parseString(str) as JsonObject
// 数组中加入number成员
jsonArray.add(1)
// 数组中加入string成员
jsonArray.add('a')
// 数组中加入数组成员
jsonArray.add(emptyArray)
// 数组中加入jsonObj成员
jsonArray.add(jsonObj)
// 序列化jsonArray并打印
let obj = new Gson().toJson(jsonArray)
console.info(`Demo JsonArray序列化:${obj.toString()}`)
- 反序列化JsonArray
// 通过str反序列化成JsonArray
let arrayStr = `[1,"a",[],{"code":400,"message":"参数错误"}]`
let jsonArray: JsonArray = parseString(arrayStr) as JsonArray
console.info(`Demo size = ${jsonArray.size()}`)
// 获取JsonArray中的第一个值并打印
let value0 = (jsonArray.get(0) as JsonPrimitive).getAsNumber()
console.info(`Demo value0:${value0}`)
// 获取JsonArray中的第二个值并打印
let value1 = (jsonArray.get(1) as JsonPrimitive).getAsString()
console.info(`Demo value1:${value1}`)
// 获取JsonArray中的第三个值并打印
let value2 = (jsonArray.get(2) as JsonArray)
let obj = new Gson().toJson(value2)
console.info(`Demo value2:${obj.toString()}`)
// 获取JsonArray中的第四个值并打印
let value3 = (jsonArray.get(3) as JsonObject)
let code = value3.getAsJsonPrimitiveByMemberName('code').getAsNumber()
let message = value3.getAsJsonPrimitiveByMemberName('message').getAsString()
console.info(`Demo code:${code} message:${message}`)
更多关于HarmonyOS鸿蒙Next中实现Gson集成示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中集成Gson库,可以通过以下步骤实现:
-
添加依赖:在
build.gradle
文件中添加Gson库的依赖。dependencies { implementation 'com.google.code.gson:gson:2.8.6' }
-
创建数据类:定义一个数据类,用于序列化和反序列化。
public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } // Getters and setters }
-
序列化:将对象转换为JSON字符串。
Gson gson = new Gson(); User user = new User("John", 30); String json = gson.toJson(user);
-
反序列化:将JSON字符串转换为对象。
String json = "{\"name\":\"John\",\"age\":30}"; User user = gson.fromJson(json, User.class);
-
处理复杂对象:对于包含嵌套对象或列表的对象,Gson同样支持。
public class Address { private String city; private String street; public Address(String city, String street) { this.city = city; this.street = street; } // Getters and setters } public class User { private String name; private int age; private Address address; public User(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } // Getters and setters } Gson gson = new Gson(); User user = new User("John", 30, new Address("New York", "5th Avenue")); String json = gson.toJson(user);
-
处理日期:Gson支持自定义日期格式。
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
通过以上步骤,你可以在HarmonyOS鸿蒙Next中成功集成并使用Gson库进行JSON数据的序列化和反序列化。
更多关于HarmonyOS鸿蒙Next中实现Gson集成示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中集成Gson库,首先需要在build.gradle
文件中添加Gson依赖:
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
然后,可以在代码中使用Gson进行JSON的序列化和反序列化。以下是一个简单的示例:
import com.google.gson.Gson;
public class User {
private String name;
private int age;
// 构造函数、getter和setter省略
public static void main(String[] args) {
User user = new User();
user.setName("John");
user.setAge(30);
Gson gson = new Gson();
String json = gson.toJson(user); // 序列化
System.out.println(json);
User deserializedUser = gson.fromJson(json, User.class); // 反序列化
System.out.println(deserializedUser.getName());
}
}
通过这种方式,你可以在HarmonyOS中轻松使用Gson处理JSON数据。