颤振中的JSON对象映射器
我希望在flatter中从JSON序列化/反序列化对象。我知道我可以使用颤振中的JSON对象映射器,json,dart,jsonserializer,objectmapper,flutter,Json,Dart,Jsonserializer,Objectmapper,Flutter,我希望在flatter中从JSON序列化/反序列化对象。我知道我可以使用json.dart中的jsondeconder,它给了我基于字符串键的LinkedHashMap,但我更感兴趣的是ObjectMapper方法,这样我就能够从反序列化中得到类型化的响应 我用flatter尝试了redstone mapper()和exportable library()——这两个我都无法正确编译。我相信这个问题与Dart的反射库有关 如何使用flatter实现工作对象Json映射器 示例代码: class A
json.dart
中的jsondeconder
,它给了我基于字符串键的LinkedHashMap,但我更感兴趣的是ObjectMapper方法,这样我就能够从反序列化中得到类型化的响应
我用flatter尝试了redstone mapper()和exportable library()——这两个我都无法正确编译。我相信这个问题与Dart的反射库有关
如何使用flatter实现工作对象Json映射器
示例代码:
class A {
@Field()
String b;
}
import 'package:redstone_mapper/mapper.dart';
import 'package:redstone_mapper/mapper_factory.dart';
bootstrapMapper();
var desObj = decodeJson(jsonString, A);
错误:
Starting device daemon...
Running lib/main.dart on Nexus 5X...
Dart snapshot generator failed with exit code 254
Errors encountered while loading: 'dart:mirrors': error: line 1 pos 1: unexpected token 'Unhandled'
或者这个:
Error detected in application source code:
error: Failed to load main script:
'package:redstone_mapper/mapper_factory.dart': error: line 4 pos 1: import of dart:mirrors with --enable-mirrors=false
import 'dart:mirrors';
您尝试的库存在的问题是它们使用的是
dart:mirrors
,这在flatter上不受支持
您应该尝试一个使用codegen的库,例如
内置值
:您尝试的库存在的问题是它们使用的是省道:镜像
,这在颤振上不受支持
您应该尝试使用codegen的库,例如@HarryTerkelsen建议的
builded_value
:,Google提供了builded_value库
可以找到序列化示例。
缺点是build_value使用生成的*.g.dart类来创建序列化程序,所以这个库不是一个简单的“导入并运行”的东西
有一个示例项目展示了集合序列化。还有
简而言之,您需要运行以生成序列化程序
编辑:
最后,我从头开始编写了简单的序列化:
import 'dart:convert';
class ItemDescription {
String tag;
String name;
static ItemDescription deserialize(String str) {
JsonDecoder decoder = new JsonDecoder();
var deserializedMap = decoder.convert(str);
return deserialize(deserializedMap);
}
static ItemDescription deserializeMap(Map map) {
ItemDescription description = new ItemDescription();
description.name = map["name"];
description.tag = map["symbol"];
return description;
}
}
正如@HarryTerkelsen所说,谷歌提供了内置价值库 可以找到序列化示例。 缺点是build_value使用生成的*.g.dart类来创建序列化程序,所以这个库不是一个简单的“导入并运行”的东西 有一个示例项目展示了集合序列化。还有 简而言之,您需要运行以生成序列化程序 编辑: 最后,我从头开始编写了简单的序列化:
import 'dart:convert';
class ItemDescription {
String tag;
String name;
static ItemDescription deserialize(String str) {
JsonDecoder decoder = new JsonDecoder();
var deserializedMap = decoder.convert(str);
return deserialize(deserializedMap);
}
static ItemDescription deserializeMap(Map map) {
ItemDescription description = new ItemDescription();
description.name = map["name"];
description.tag = map["symbol"];
return description;
}
}
使用这个库不仅仅是添加一个简单的
'import'
语句。使用此库查找我的答案不仅仅是添加一个简单的'import'
语句。如果“反序列化”方法的最后一行调用的是“deserializeMap”,而不是其本身,请查看我的答案?请您添加一个如何使用该方法的示例。提前感谢“deserialize”方法的最后一行是否应该调用“deserializeMap”,而不是它本身?请您添加一个如何使用它的示例。提前谢谢