I have successfully deserialized my json file. I have stored one element of the json in one object successfully , but i am getting a problem storing the objects in a list.
I tried every possible solution from the internet below you will see the trials i have made.
This is my code
class _MyHomePageState extends State<MyHomePage> {
String? _chosenSubCounty;
List<County> counties = [];
Future<String> getJson() async {
final jsonResult = await rootBundle.loadString('assets/json_files/counties.json');
List<dynamic> parsedListJson = jsonDecode(jsonResult);
print(parsedListJson[0]);//prints {name: Baringo, capital: Kabarnet, code: 30, sub_counties: [Baringo central, Baringo north, Baringo south, Eldama ravine, Mogotio, Tiaty]}
final county = County.fromJson(parsedListJson[0]);
print(county.name.toString());//prints Baringo
//trial no 1 failed
counties = parsedListJson.map((i)=>County.fromJson(i)).toList();
//trial no 2 also failed
counties = List<County>.from(parsedListJson.map((i) => County.fromJson(i)));
//trial no 3 also failed
for(int i = 0; i < parsedListJson.length; i ){
counties.add(County.fromJson(parsedListJson[i]));
}
print(counties);//prints Error: Expected a value of type 'String', but got one of type 'Null'
return jsonResult;
}
@override
void initState() {
getJson();
}
@override
Widget build(BuildContext context) {..........}
}
This is Model Class
import 'dart:convert';
List<County> countyFromJson(String str) => List<County>.from(json.decode(str).map((x) => County.fromJson(x)));
String countyToJson(List<County> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class County {
String name;
String capital;
int code;
List subCounties;
County({
required this.name,
required this.capital,
required this.code,
required this.subCounties,
});
factory County.fromJson(Map<String, dynamic> json) {
return County(
name: json["name"],
capital: json["capital"],
code: json["code"],
subCounties: List<String>.from(json["sub_counties"])
);
}
Map<String, dynamic> toJson() => {
"name": name,
"capital": capital == null ? null : capital,
"code": code,
"sub_counties": List<dynamic>.from(subCounties.map((x) => x)),
};
}
This is the json file
[
{
"name": "Baringo",
"capital": "Kabarnet",
"code": 30,
"sub_counties": [
"Baringo central",
"Baringo north",
"Baringo south",
"Eldama ravine",
"Mogotio",
"Tiaty"
]
},
{
"name": "Bomet",
"capital": "Bomet",
"code": 36,
"sub_counties": [
"Bomet central",
"Bomet east",
"Chepalungu",
"Konoin",
"Sotik"
]
},
]
CodePudding user response:
First remove comma after your 2nd json Object from your json file. Then use this code to parse your json. I've run the project and it works totally fine.
import 'package:flutter/material.dart';
import 'package:stacksolution/county_model.dart';
class FetchData extends StatefulWidget {
const FetchData({Key? key}) : super(key: key);
@override
_FetchDataState createState() => _FetchDataState();
}
class _FetchDataState extends State<FetchData> {
@override
void initState() {
// TODO: implement initState
callJson();
super.initState();
}
callJson() async {
String jsonString =
await DefaultAssetBundle.of(context).loadString('assets/county.json');
List<CountyModel> list = countyFromJson(jsonString);
print("$list");
}
@override
Widget build(BuildContext context) {
return Container();
}
}
The Model class:
import 'dart:convert';
List<CountyModel> countyFromJson(String str) => List<CountyModel>.from(
json.decode(str).map((x) => CountyModel.fromJson(x)));
String countyToJson(List<CountyModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountyModel {
CountyModel({
this.name,
this.capital,
this.code,
this.subCounties,
});
String? name;
String? capital;
int? code;
List<String>? subCounties;
factory CountyModel.fromJson(Map<String, dynamic> json) => CountyModel(
name: json["name"],
capital: json["capital"],
code: json["code"],
subCounties: List<String>.from(json["sub_counties"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"name": name,
"capital": capital,
"code": code,
"sub_counties": List<dynamic>.from(subCounties!.map((x) => x)),
};
}
The Json File:
[
{
"name": "Baringo",
"capital": "Kabarnet",
"code": 30,
"sub_counties": [
"Baringo central",
"Baringo north",
"Baringo south",
"Eldama ravine",
"Mogotio",
"Tiaty"
]
},
{
"name": "Bomet",
"capital": "Bomet",
"code": 36,
"sub_counties": [
"Bomet central",
"Bomet east",
"Chepalungu",
"Konoin",
"Sotik"
]
}
]