JSON(JavaScript Object Notation) 이란?
데이터를 저장하거나 전송할 때 많이 사용되는 경량의 DATA 교환 형식
보통 서버(백엔드)와 클라이언트(프론트엔드) 간의 교류에서 일반적으로 많이 사용
import
import 'package:http/http.dart' as http;
Class
class Info {
final String seq;
final String educ_name;
final String image;
final String cat;
final String sub_cat;
Info({
required this.seq,
required this.educ_name,
required this.image,
required this.cat,
required this.sub_cat,
});
// fromJson(): JSON 개체로 시작을 쉽게 만들 수 있도록 팩토리 메서드를 포함
// factory 메서드란 객체를 생성 반환하는 메서드
factory Info.fromJson(Map<String, dynamic> json) {
return Info(
seq: json["seq"],
educ_name: json["educ_name"],
image: json["image"],
cat: json["cat"],
sub_cat: json["sub_cat"],
);
}
}
Json 파싱
Future<List<Info>> fetchInfo() async {
// async를 해준 이유는 http의 get() 함수가 await 를 포함하고 있어, 비동기가 되기 때문
var url = 'http://xxx.xx.xxx.xx/api/container.php?language=1';
final response = await http.post(Uri.parse(url));
// 네트워크 요청하기 - JSON 문서를 가져오는 방법
if (response.statusCode == 200) {
//200: HTTP 서버 요청이 성공
//만약 서버가 ok응답을 반환하면, json을 파싱합니다
//print(json.decode(response.body));
Map<String, dynamic> map = json.decode(response.body);
// url의 데이터를 response.body에 담아 사용
List<dynamic> body = map["result"];
List<Info> allInfo =
body.map((dynamic item) => Info.fromJson(item)).toList();
// allInfo - Json문서를 변환
return allInfo;
} else {
//만약 응답이 ok가 아니면 에러를 던집니다.
throw Exception("네트워크 오류");
}
}