我目前正在使用json_annotation和json_serializable来解析json,但不确定如何将原始json字符串转换为dart对象。
part 'message.g.dart';
@JsonSerializable(nullable: false)
class Message extends Model {
Message(this.title, this.message);
final String title;
final String message;
static const fromJsonFactory = _$MessageFromJson;
Map<String, dynamic> toJson() => _$MessageToJson(this);
}
我要实现的目标如下:
String json = '[{"title":"message1","message":"message1 substitle"},{"title":"message2","message":"message2 substitle"}]';
List<Message> messages = Message.listFromJson(json);
像这样可能吗?无需手动编写映射器。现在,我有一个具有两个属性的示例,但实际上,一个消息对象包含30多个属性。
我已经在使用chopper json可序列化转换器。但是我不确定我如何才能重写它以便仅用于json字符串而不是响应。
import 'package:chopper/chopper.dart';
import 'package:flutter_app/base/util/log.dart';
typedef T JsonFactory<T>(Map<String, dynamic> json);
class JsonSerializableConverter extends JsonConverter {
final Map<Type, JsonFactory> factories;
JsonSerializableConverter(this.factories);
T _decodeMap<T>(Map<String, dynamic> values) {
/// Get jsonFactory using Type parameters
/// if not found or invalid, throw error or return null
final jsonFactory = factories[T];
if (jsonFactory == null || jsonFactory is! JsonFactory<T>) {
/// throw serializer not found error;
return null;
}
return jsonFactory(values);
}
List<T> _decodeList<T>(List values) =>
values.where((v) => v != null).map<T>((v) => _decode<T>(v)).toList();
dynamic _decode<T>(entity) {
if (entity is Iterable) return _decodeList<T>(entity);
if (entity is Map) return _decodeMap<T>(entity);
return entity;
}
@override
Response<ResultType> convertResponse<ResultType, Item>(Response response) {
// use [JsonConverter] to decode json
final jsonRes = super.convertResponse(response);
log("json res body");
log(jsonRes.body.runtimeType);
return jsonRes.replace<ResultType>(body: _decode<Item>(jsonRes.body));
}
@override
// all objects should implements toJson method
Request convertRequest(Request request) => super.convertRequest(request);
Response convertError<ResultType, Item>(Response response) {
// use [JsonConverter] to decode json
// final jsonRes = super.convertError(response);
//
// return jsonRes.replace<ResourceError>(
// body: ResourceError.fromJsonFactory(jsonRes.body),
// );
return response;
}
}