[Json 예시]
{ "status": "success", "data": { "city": "Yongsan-dong", "state": "Seoul", "country": "South Korea", "location": { "type": "Point", "coordinates": [ 126.990597, 37.532171 ] }, "current": { "pollution": { "ts": "2022-10-09T08:00:00.000Z", "aqius": 17, "mainus": "p2", "aqicn": 17, "maincn": "n2" }, "weather": { "ts": "2022-10-09T08:00:00.000Z", "tp": 12, "pr": 1015, "hu": 89, "ws": 2.57, "wd": 135, "ic": "10d" } } } }
[방법1. Json to Dart 사이트 사용하기]
https://javiercbk.github.io/json_to_dart/
- 왼쪽에 Json 을 넣으면
- 오른쪽에 자동으로 Json 을 모델화 한 Class.dart 파일을 생성해준다.
- 이것을 그대로 모두 복사해서 사용하면 됨 개꿀임.
[방법2. Android Studio 의 JsonToDart (Json To Dart)]
- 안드로이드 스튜디오의 Plugin 중 JsonToDart를 다운로드
- 새로운 다트 파일 만들기 들어가서 Json To Dart를 선택
- Json 입력하고 생성할 클래스명 입력하면 자동으로 모델 생성해줌 개꿀임
[방법3. json_serializable 라이브러리 사용]
- https://pub.dev/packages/json_serializable
- https://github.com/google/json_serializable.dart/tree/master/example 여기서 ReadMe에서 패키지 다운방법 사용하셈 ㅇㅋ?
dependencies: json_annotation: ^4.4.0 dev_dependencies: build_runner: ^2.0.0 json_serializable: ^6.0.0
이런식으로 패키지 다운 받으셈
[방법3. json_serializable 라이브러리 사용 자세히 보기]
- 이 방법은 어느정도 내가 코드를 짜야함 거의 다 짜야한다고 보면 됨.
import 'package:json_annotation/json_annotation.dart';
part 'AirResult2.g.dart'; //이거는 스크립트명임 스크립트당 1줄만 쓰는거임 클래스 수대로 쓰는거 아님
@JsonSerializable() // 이거 꼭 붙히삼
class AirResult2 {
final String? status;
final Data? data;
AirResult2(this.status, this.data);
factory AirResult2.fromJson(Map<String, dynamic> json) =>
_$AirResult2FromJson(json);
Map<String, dynamic> toJson() => _$AirResult2ToJson(this);
}
이거는 클래스 하나로 표현할 수 있는 완전 간단한 Json 일때의 형식이다.
하기는 맨 위의 Json 파일에 해당하는 모델 클래스 보여줌.
import 'package:json_annotation/json_annotation.dart';
part 'AirResult2.g.dart';
@JsonSerializable()
class AirResult2 {
final String? status;
final Data? data;
AirResult2(this.status, this.data);
factory AirResult2.fromJson(Map<String, dynamic> json) =>
_$AirResult2FromJson(json);
Map<String, dynamic> toJson() => _$AirResult2ToJson(this);
}
@JsonSerializable()
class Data {
final String? city;
final String? state;
final String? country;
final Location? location;
final Current? current;
Data(this.city, this.state, this.country, this.location, this.current);
factory Data.fromJson(Map<String, dynamic> json) => _$DataFromJson(json);
Map<String, dynamic> toJson() => _$DataToJson(this);
}
@JsonSerializable()
class Location {
final String? type;
final List<double>? coordinates;
Location(this.type, this.coordinates);
factory Location.fromJson(Map<String, dynamic> json) =>
_$LocationFromJson(json);
Map<String, dynamic> toJson() => _$LocationToJson(this);
}
@JsonSerializable()
class Current {
final Pollution? pollution;
final Weather? weather;
Current(this.pollution, this.weather);
factory Current.fromJson(Map<String, dynamic> json) =>
_$CurrentFromJson(json);
Map<String, dynamic> toJson() => _$CurrentToJson(this);
}
@JsonSerializable()
class Pollution {
final String? ts;
final int? aqius;
final String? mainus;
final int? aqicn;
final String? maincn;
Pollution(this.ts, this.aqius, this.mainus, this.aqicn, this.maincn);
factory Pollution.fromJson(Map<String, dynamic> json) =>
_$PollutionFromJson(json);
Map<String, dynamic> toJson() => _$PollutionToJson(this);
}
@JsonSerializable()
class Weather {
final String? ts;
final int? tp;
final int? pr;
final int? hu;
final double? ws;
final int? wd;
final String? ic;
Weather(this.ts, this.tp, this.pr, this.hu, this.ws, this.wd, this.ic);
factory Weather.fromJson(Map<String, dynamic> json) =>
_$WeatherFromJson(json);
Map<String, dynamic> toJson() => _$WeatherToJson(this);
}
- ㅇㅋ??? 이렇게 짜셈 복사해서 쓰셈 ㅇㅋ??
이거 짠 다음에
터미널에
flutter pub run build_runner build
- 실행하셈
- 그러면 진짜 Json to dart 모델 클래스 생성해줌 ㅇㅋ??
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'AirResult2.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AirResult2 _$AirResult2FromJson(Map<String, dynamic> json) => AirResult2(
json['status'] as String?,
json['data'] == null
? null
: Data.fromJson(json['data'] as Map<String, dynamic>),
);
Map<String, dynamic> _$AirResult2ToJson(AirResult2 instance) =>
<String, dynamic>{
'status': instance.status,
'data': instance.data,
};
Data _$DataFromJson(Map<String, dynamic> json) => Data(
json['city'] as String?,
json['state'] as String?,
json['country'] as String?,
json['location'] == null
? null
: Location.fromJson(json['location'] as Map<String, dynamic>),
json['current'] == null
? null
: Current.fromJson(json['current'] as Map<String, dynamic>),
);
Map<String, dynamic> _$DataToJson(Data instance) => <String, dynamic>{
'city': instance.city,
'state': instance.state,
'country': instance.country,
'location': instance.location,
'current': instance.current,
};
Location _$LocationFromJson(Map<String, dynamic> json) => Location(
json['type'] as String?,
(json['coordinates'] as List<dynamic>?)
?.map((e) => (e as num).toDouble())
.toList(),
);
Map<String, dynamic> _$LocationToJson(Location instance) => <String, dynamic>{
'type': instance.type,
'coordinates': instance.coordinates,
};
Current _$CurrentFromJson(Map<String, dynamic> json) => Current(
json['pollution'] == null
? null
: Pollution.fromJson(json['pollution'] as Map<String, dynamic>),
json['weather'] == null
? null
: Weather.fromJson(json['weather'] as Map<String, dynamic>),
);
Map<String, dynamic> _$CurrentToJson(Current instance) => <String, dynamic>{
'pollution': instance.pollution,
'weather': instance.weather,
};
Pollution _$PollutionFromJson(Map<String, dynamic> json) => Pollution(
json['ts'] as String?,
json['aqius'] as int?,
json['mainus'] as String?,
json['aqicn'] as int?,
json['maincn'] as String?,
);
Map<String, dynamic> _$PollutionToJson(Pollution instance) => <String, dynamic>{
'ts': instance.ts,
'aqius': instance.aqius,
'mainus': instance.mainus,
'aqicn': instance.aqicn,
'maincn': instance.maincn,
};
Weather _$WeatherFromJson(Map<String, dynamic> json) => Weather(
json['ts'] as String?,
json['tp'] as int?,
json['pr'] as int?,
json['hu'] as int?,
(json['ws'] as num?)?.toDouble(),
json['wd'] as int?,
json['ic'] as String?,
);
Map<String, dynamic> _$WeatherToJson(Weather instance) => <String, dynamic>{
'ts': instance.ts,
'tp': instance.tp,
'pr': instance.pr,
'hu': instance.hu,
'ws': instance.ws,
'wd': instance.wd,
'ic': instance.ic,
};
- 어디서 많이 본 코드일 것이다. 이거 위의 방법1 , 방법2 에서 한방에 생성해준 코드임ㅋㅋㅋㅋㅋ
근데 왜 라이브러리 쓰는거임? 사이트랑 플러그인으로 한방에 모델 클래스 생성하고 말지ㅋㅋㅋ
맞는 말이긴 한데 이건 어느정도 사용자화 커스텀이 가능하더라 ㅋㅋ
솔직히 맘에 드는거 쓰셈 ㅇㅋ??