- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在开发一个使用 Flutter 制作的移动项目。该项目需要连接到一些服务器以进行 REST 消费服务(GET、POST、PUT、DELETE,...),并检索数据以及向它们发送数据。数据需要以 JSON 格式格式化,因此我决定将 Json 序列化库 2.0.3 用于 Dart,并带有 Json 注释 2.0.0 和 build_runner 1.2.8;它确实适用于 int、String 和 bool 等基本数据类型以及自定义对象。但它似乎根本不适用于泛型,例如 <T> item;
例如字段或 List<T> list;
字段。
我的目的是添加一些通用字段,以便它们可以用于返回所有类型的 json 类型和结构。我设法为第一种情况找到了解决方案,通过使用“@JsonKey”覆盖 fromJson 和 toJson,并比较 <T>
我想在方法中将其转换为所需的类型。但是,我找不到 List<T>
的解决方案类型字段。如果我尝试为它们使用注释,我得到的只是 List<dynamic>
类型对于比较类型转换类是无用的。我该如何解决我的困境?我应该坚持使用 json_serialization 还是改用 build_value ?非常感谢您对此事的任何帮助。
我的代码:
import 'package:json_annotation/json_annotation.dart';
part 'json_generic.g.dart';
@JsonSerializable()
class JsonGeneric<T> {
final int id;
final String uri;
final bool active;
@JsonKey(fromJson: _fromGenericJson, toJson: _toGenericJson)
final T item;
@JsonKey(fromJson: _fromGenericJsonList, toJson: _toGenericJsonList)
final List<T> list;
static const String _exceptionMessage = "Incompatible type used in JsonEnvelop";
JsonGeneric({this.id, this.uri, this.active, this.item, this.list});
factory JsonGeneric.fromJson(Map<String, dynamic> json) =>
_$JsonGenericFromJson(json);
Map<String, dynamic> toJson() => _$JsonGenericToJson(this);
static T _fromGenericJson<T>(Map<String, dynamic> json) {
if (T == User) {
return json == null ? null : User.fromJson(json) as T;
} else if (T == Company) {
return json == null ? null : Company.fromJson(json) as T;
} else if (T == Data) {
return json == null ? null : Data.fromJson(json) as T;
} else {
throw Exception(_exceptionMessage);
}
}
static Map<String, dynamic> _toGenericJson<T>(T value) {
if (T == User) {
return (T as User).toJson();
} else if(T == Company) {
return (T as Company).toJson();
} else if(T == Data) {
return (T as Data).toJson();
} else {
throw Exception(_exceptionMessage);
}
}
static dynamic _fromGenericJsonList<T>(List<dynamic> json) {
if (T == User) {
} else if(T == Company) {
} else if(T == Data) {
} else {
throw Exception(_exceptionMessage);
}
}
static List<Map<String, dynamic>> _toGenericJsonList<T>(dynamic value) {
if (T == User) {
} else if(T == Company) {
} else if(T == Data) {
} else {
throw Exception(_exceptionMessage);
}
}
}
我希望能够序列化/反序列化“最终列表列表;”使用“@JsonKey”或不使用它,但到目前为止,我未能找到将其转换为正确 json 格式的方法。
当我尝试为此类生成代码时(使用命令“flutter packages pub run build_runner build”),我最终收到以下错误:
运行 JsonSerializableGenerator 时出错无法生成 fromJson
list
的代码因为类型 T
.没有提供TypeHelper
实例支持定义的类型。包:json_generic.dart:11:17
╷
11 │ final List<T> list;
│ ^^^^
╵
最佳答案
这是一个例子
https://github.com/dart-lang/json_serializable/blob/master/example/lib/json_converter_example.dart
//json_converter_example.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
part 'json_converter_example.g.dart';
@JsonSerializable()
class GenericCollection<T> {
@JsonKey(name: 'page')
final int page;
@JsonKey(name: 'total_results')
final int totalResults;
@JsonKey(name: 'total_pages')
final int totalPages;
@JsonKey(name: 'results')
@_Converter()
final List<T> results;
GenericCollection(
{this.page, this.totalResults, this.totalPages, this.results});
factory GenericCollection.fromJson(Map<String, dynamic> json) =>
_$GenericCollectionFromJson<T>(json);
Map<String, dynamic> toJson() => _$GenericCollectionToJson(this);
}
class _Converter<T> implements JsonConverter<T, Object> {
const _Converter();
@override
T fromJson(Object json) {
if (json is Map<String, dynamic> &&
json.containsKey('name') &&
json.containsKey('size')) {
return CustomResult.fromJson(json) as T;
}
if (json is Map<String, dynamic> &&
json.containsKey('name') &&
json.containsKey('lastname')) {
return Person.fromJson(json) as T;
}
// This will only work if `json` is a native JSON type:
// num, String, bool, null, etc
// *and* is assignable to `T`.
return json as T;
}
@override
Object toJson(T object) {
// This will only work if `object` is a native JSON type:
// num, String, bool, null, etc
// Or if it has a `toJson()` function`.
return object;
}
}
@JsonSerializable()
class CustomResult {
final String name;
final int size;
CustomResult(this.name, this.size);
factory CustomResult.fromJson(Map<String, dynamic> json) =>
_$CustomResultFromJson(json);
Map<String, dynamic> toJson() => _$CustomResultToJson(this);
@override
bool operator ==(Object other) =>
other is CustomResult && other.name == name && other.size == size;
@override
int get hashCode => name.hashCode * 31 ^ size.hashCode;
}
@JsonSerializable()
class Person {
final String name;
final String lastname;
Person(this.name, this.lastname);
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
@override
bool operator ==(Object other) =>
other is Person && other.name == name && other.lastname == lastname;
}
//main.dart
import './json_converter_example.dart';
import 'dart:convert';
final jsonStringCustom =
'''{"page":1,"total_results":10,"total_pages":200,"results":[{"name":"Something","size":80},{"name":"Something 2","size":200}]}''';
final jsonStringPerson =
'''{"page":2,"total_results":2,"total_pages":300,"results":[{"name":"Arya","lastname":"Stark"},{"name":"Night","lastname":"King"}]}''';
void main() {
// Encode CustomResult
List<CustomResult> results;
results = [CustomResult("Mark", 223), CustomResult("Albert", 200)];
// var customResult = List<CustomResult> data;
var jsonData = GenericCollection<CustomResult>(
page: 1, totalPages: 200, totalResults: 10, results: results);
print({'JsonString', json.encode(jsonData)});
// Decode CustomResult
final genericCollectionCustom =
GenericCollection<CustomResult>.fromJson(json.decode(jsonStringCustom));
print({'name', genericCollectionCustom.results[0].name});
// Encode Person
List<Person> person;
person = [Person("Arya", "Stark"), Person("Night", "King")];
var jsonDataPerson = GenericCollection<Person>(
page: 2, totalPages: 300, totalResults: 2, results: person);
print({'JsonStringPerson', json.encode(jsonDataPerson)});
// Decode Person
final genericCollectionPerson =
GenericCollection<Person>.fromJson(json.decode(jsonStringPerson));
print({'name', genericCollectionPerson.results[0].name});
}
结果
{JsonStringCustom, {"page":1,"total_results":10,"total_pages":200,"results":[{"name":"Mark","size":223},{"name":"Albert","size":200}]}}
{name, Something}
{JsonStringPerson, {"page":2,"total_results":2,"total_pages":300,"results":[{"name":"Arya","lastname":"Stark"},{"name":"Night","lastname":"King"}]}}
{name, Arya}
关于json - 如何在 Dart 中使用带有 json 序列化的泛型和泛型列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55306746/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!