Flutter에서 객체를 json으로 인코딩하는 방법
개체 "Week"를 json으로 변환하려고 합니다.
https://dev/dev/dev/development/data-and-dev/json 이것은 제가 사용한 소스입니다.
class Week{
DateTime _startDate;
DateTime _endDate;
List<Goal> _goalList;
String _improvement;
Week(this._startDate, this._endDate){
this._goalList = List<Goal>();
this._improvement = "";
}
Week.fromJson(Map<String, dynamic> json)
: _startDate = json['startDate'],
_endDate = json['endDate'],
_goalList = json['goalList'],
_improvement = json['improvement'];
Map<String, dynamic> toJson() =>
{
'startDate': _startDate,
'endDate': _endDate,
'goalList': _goalList,
'improvement': _improvement,
};
}
저는 이걸 썼어요
DateTime startDate = currentDate.subtract(new Duration(days:(weekday-1)));
DateTime endDate = currentDate.add(new Duration(days:(7-weekday)));
Week week = new Week(startDate, endDate);
var json = jsonEncode(week);
하지만 문제는 다음과 같은 결과가 나온다는 것입니다.
Unhandled Exception: Converting object to an encodable object failed: Instance of 'Week'
#0 _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:834:17)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:819:5)
#3 JsonEncoder.convert (dart:convert/json.dart:255:30)
#4 JsonCodec.encode (dart:convert/json.dart:166:45)
#5 jsonEncode (dart:convert/json.dart:80:10)
jsonEncode에는 다음이 필요합니다.Map<String, dynamic>, 가 아닙니다.Week물건.고객님께 전화드립니다.toJson()방법이 효과가 있을 것입니다.
var json = jsonEncode(week.toJson());
단, 주의해 주십시오.toJson()_goalList나 날짜 등은 맵이나 목록이 아닌 오브젝트이기 때문에 메서드도 올바르지 않습니다.이러한 경우에도 ToJson 메서드를 구현해야 합니다.
특정 질문에 답변하려면:
- 다트는 javascript/typescript가 아니기 때문입니다.Dart는 런타임에 타입을 체크하기 때문에 변환 방법을 명시적으로 가르쳐야 합니다.또한 Dart에는 반사도 없기 때문에 스스로는 알 수 없습니다.
- 코드 생성을 사용하는 라이브러리를 사용하여 이러한 작업을 자동으로 수행할 수 있습니다. 그러나 런타임에는 여전히 가능하지 않습니다. JSON 직렬화에 대한 자세한 내용은 참조하십시오.
- 가장 쉬운 방법은 메소드를 클래스에 직접 구현하는 것입니다. 이 클래스는 루트 개체에서 액세스할 수 있기 때문입니다.이 구조에서는,
jsonEncode니즈는Map<String, dynamic>단,dynamic파트의 진정한 의미List<dynamic>,Map<String, dynamic>또는 다음과 같은 json 호환성이 있는 원시입니다.String또는double- 이렇게 중첩된 구조가 어떻게 보일지 상상해보면, 기본적으로 json이라는 것을 알 수 있을 것이다.그래서 이런 걸 할 때'goalList': _goalList,오브젝트를 부여하고 있지만 이는 허용되지 않는 유형입니다.
이걸로 일이 좀 해결됐으면 좋겠다.
궁금하신 분들을 위해:난 내 해결책을 얻었다.
내 코드를 작동시키기 위해서는toJson()우리 반의 방법Goal(사용했기 때문에)List<Goal>에Week).
class Goal{
String _text;
bool _reached;
Map<String, dynamic> toJson() =>
{
'text': _text,
'reached': _reached,
};
}
그리고 나는 더해야 했다..toIso8601String()에게DateTime에 있는 것과 같은 물건Week클래스:
Map<String, dynamic> toJson() =>
{
'startDate': _startDate.toIso8601String(),
'endDate': _endDate.toIso8601String(),
'goalList': _goalList,
'improvement': _improvement,
};
출력은 다음과 같습니다.
{"startDate":"2019-05-27T00:00:00.000Z","endDate":"2019-06-02T00:00:00.000Z","goalList":[],"improvement":""}
위의 @Phillip의 답변에서 Json 시리얼라이제이션에 대한 제안 2를 인용하면, Freezed 패키지는 건너뛸 수 있습니다.@JsonSerializable주석과 단지 사용했을 뿐입니다.@Freezed"Json/toJson에서 필요한 모든 것을 생성하도록 json_serializable에 자동으로 요청합니다."예를 들어 https://flutter.dev/docs/development/data-and-backend/json#use-code-generation-to-large-projects는 다음과 같습니다.
//import 'package:json_annotation/json_annotation.dart';
import 'freezed_annotation/freezed_annotation.dart';
/// This allows the `User` class to access private members in
/// the generated file. The value for this is *.g.dart, where
/// the star denotes the source file name.
part 'user.g.dart';
part 'user.freezed.dart';
/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@freezed
class User {
User(this.name, this.email);
String name;
String email;
/// A necessary factory constructor for creating a new User instance
/// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
/// The constructor is named after the source class, in this case, User.
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
/// `toJson` is the convention for a class to declare support for serialization
/// to JSON. The implementation simply calls the private, generated
/// helper method `_$UserToJson`.
Map<String, dynamic> toJson() => _$UserToJson(this);
}
프리즈: https://pub.dev/packages/freezed 편집 잊지 마세요pubspec.yaml★★★★★★에freezed ★★★★★★★★★★★★★★★★★」freezed_annotation
언급URL : https://stackoverflow.com/questions/56406601/how-to-encode-an-object-to-json-in-flutter
'programing' 카테고리의 다른 글
| Maven이 Java 11을 사용하지 않음: 오류 메시지 "Fatal error compiling: invalid target release: 11" (0) | 2023.04.05 |
|---|---|
| C++: nlohmann json을 사용하여 파일에서 json 개체 읽기 (0) | 2023.04.05 |
| WordPress를 사용한 Git 워크플로우 - Localhost to Live (0) | 2023.03.31 |
| 재료 UI 아이콘을 가져오려면 어떻게 해야 합니까?재료 UI 아이콘을 사용하는 중에 문제가 발생했습니다. (0) | 2023.03.31 |
| jQuery AJAX 요청을 취소/중지하는 방법 (0) | 2023.03.31 |