Reputation: 131
Here is my class
class Prod {
int? pCode;
String? pName;
String? pIdCode;
int? pGCode;
String? pGName;
int? pGCategory;
String? pPack;
double? pRate;
String? pDisc;
String? pImage;
Prod({pCode, pName, pIdCode, pGCode,pGName, pGCategory, pPack, pRate, pDisc, pImage});
}
JSON Data Retrived from Server
{"status":1,"msg":"OK","ProdList":[{"PCode":"1812","PName":"3D STICKER - 1 - CFK3S02","PIdCode":"CFK\/3S-02","PGCode":"116","PGName":"3D STICKERS (K)","PGCategory":"1","PPack":"1 PACK","PRate":"50.00","PDisc":"NOT AVAILABEL","PImage":"STICKER 3D - 1.jpeg"},{"PCode":"1803","PName":"3D STICKER - 2 - CFK3S02","PIdCode":"CFK3S-02","PGCode":"116","PGName":"3D STICKERS (K)","PGCategory":"1","PPack":"1 PACK","PRate":"50.00","PDisc":"BEAUTIFUL STICKERS IN VARIOUS DESIGNS.","PImage":"STICKER 3D - 2.jpeg"}]}
Flutter Code to Read Data
Future fetchProd() async {
var client = http.Client();
try {
Uri web = Uri.https("website address");
var response = await client.get(web);
if (response.statusCode == 200) {
Map result = jsonDecode(response.body) as Map;
if ((result["status"] as int) == 1) {
//Here I'm unable to figure out how to convert ProdList from Map data to List<Prod>
//=================================================================================
//Map PList = result["ProdList"] as Map;
//GlobalVariable.prodList = PList.values.toList() as List<Prod>;
}
} else {
throw Exception(response.statusCode.toString());
}
} catch (e) {
rethrow;
} finally {
client.close();
}
}
I'm unable to convert "ProdList" from JSON Map Data to List
Thanks in advance Amit Saraf
Upvotes: 0
Views: 76
Reputation: 1846
import 'dart:convert';
import 'package:http/http.dart' as http;
//You need to deserialize Json with fromMap method
class ProdList {
String? pCode;
String? pName;
String? pIdCode;
String? pGCode;
String? pGName;
String? pGCategory;
String? pPack;
String? pRate;
String? pDisc;
String? pImage;
ProdList({this.pCode, this.pName, this.pIdCode,
this.pGCode, this.pGName, this.pGCategory,
this.pPack, this.pRate, this.pDisc,
this.pImage});
ProdList.fromMap(Map<String, dynamic> map) {
pCode = map['PCode'];
pName = map['PName'];
pIdCode = map['PIdCode'];
pGCode = map['PGCode'];
pGName = map['PGName'];
pGCategory = map['PGCategory'];
pPack = map['PPack'];
pRate = map['PRate'];
pDisc = map['PDisc'];
pImage = map['PImage'];
}
}
class ApiClass{
Future<List<ProdList>> fetchUsers()async{
final response = await http.get(Uri.parse("your url"));
List listData = jsonDecode(response.body)['ProdList'];
if(response.statusCode == 200){
var result = listData.map((e) => ProdList.fromMap(e)).toList();
for(int i = 0; i<result.length; i++){
print(result[i].pGName);
}
return result;
}else{
throw Exception("Error");
}
}
}
It's hard to explain what I did here. You can check this page which explains json parsing from simple to complex json.
Upvotes: 2