gpt4 book ai didi

json - 如何在 Dart 中使用带有 json 序列化的泛型和泛型列表?

转载 作者:IT老高 更新时间:2023-10-28 12:41:49 24 4
gpt4 key购买 nike

我正在开发一个使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com