Parse a JSON array with multiple object types - flutter

Let's say I have a JSON array like this:
"videos": [
{
"id": 25182,
"game": 115653,
"name": "Trailer",
"video_id": "BdA22Lh6Rwk"
},
27749,
{
"id": 29188,
"game": 115653,
"name": "A New Team and New Rivals in Pokémon Sword and Pokémon Shield! ⚔️🛡️",
"video_id": "ZBiTpi8ecTE"
}
]
Normally if the item's JSON format in videos is like videos[0] or videos[2] then I was able to parse it to Video like this:
json['videos']?.cast<Map<String, dynamic>>()?.map<Video>((f) {
return Video.fromJson(f);
})?.toList();
My Video class:
class Video {
int id;
int game;
String name;
String videoId;
Video({this.id, this.game, this.name, this.videoId});
Video.fromJson(Map<String, dynamic> json) {
id = json['id'];
game = json['game'];
name = json['name'];
videoId = json['video_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['game'] = this.game;
data['name'] = this.name;
data['video_id'] = this.videoId;
return data;
}
}
But if something with the different structure like videos[1] is within the array then I ended up with Exception. How can I parse videos[1] to Video with video[1] as Video's id?

You have to know the different formats and figure out which one each entry is.
You can do that by checking the type of the entry: Is it an integer or a map?
Example:
List<Video> videosFromJson(List<Object> videoJson) {
var result = <Video>[];
for (int i = 0; i < videoJson.length; i++) {
var entry = videoJson[i];
if (entry is Map<String, dynamic>) {
result.add(Video.fromJson(entry));
} else if (entry is int) {
result.add(Video()..id = entry);
} else {
throw FormatException("Not a recognized video format", entry, i);
}
}
return result;
}

Related

Flutter - How to show data from Model 1 and data from Model2 in one UI

I successfully called http cho the ProductModel and now i dont know how to get the ProductDrugModel to show along with ProductModel
this is my Model1:
class ProductModel {
String productID;
String drugbankID;
String productName;
String productLabeller;
String productCode;
String productRoute;
String productStrength;
String productdosage;
String approved;
String otc;
String generic;
String country;
ProductModel(
{this.productID,
this.drugbankID,
this.productName,
this.productLabeller,
this.productCode,
this.productRoute,
this.productStrength,
this.productdosage,
this.approved,
this.otc,
this.generic,
this.country});
ProductModel.fromJson(Map<String, dynamic> json) {
productID = json['productID'];
drugbankID = json['drugbankID'];
productName = json['productName'];
productLabeller = json['productLabeller'];
productCode = json['productCode'];
productRoute = json['productRoute'];
productStrength = json['productStrength'];
productdosage = json['productdosage'];
approved = json['approved'];
otc = json['otc'];
generic = json['generic'];
country = json['country'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['productID'] = this.productID;
data['drugbankID'] = this.drugbankID;
data['productName'] = this.productName;
data['productLabeller'] = this.productLabeller;
data['productCode'] = this.productCode;
data['productRoute'] = this.productRoute;
data['productStrength'] = this.productStrength;
data['productdosage'] = this.productdosage;
data['approved'] = this.approved;
data['otc'] = this.otc;
data['generic'] = this.generic;
data['country'] = this.country;
return data;
}
}
Model2:
class ProductDrugModel {
String drugbankID;
String drugName;
String drugDescription;
String drugState;
String drugIndication;
String drugPharmaco;
String drugMechan;
String drugToxicity;
String drugMetabolism;
String drugHalflife;
String drugElimination;
String drugClearance;
ProductDrugModel({
this.drugbankID,
this.drugName,
this.drugDescription,
this.drugState,
this.drugIndication,
this.drugPharmaco,
this.drugMechan,
this.drugToxicity,
this.drugMetabolism,
this.drugHalflife,
this.drugElimination,
this.drugClearance,
});
factory ProductDrugModel.fromJson(Map<String, dynamic> json) {
return ProductDrugModel(
drugbankID: json['drugbank_ID'],
drugName: json['drugName'],
drugDescription: json['drugDescription'],
drugState: json['drugState'],
drugIndication: json['drugIndication'],
drugPharmaco: json['drugPharmaco'],
drugMechan: json['drugMechan'],
drugToxicity: json['drugToxicity'],
drugMetabolism: json['drugMetabolism'],
drugHalflife: json['drugHalflife'],
drugElimination: json['drugElimination'],
drugClearance: json['drugClearance'],
);
}
}
My api call
class RecommenedData {
static Future<List<ProductModel>> getRecommened() async {
try {
var response =
await
http.get(Uri.parse(Constants.PRODUCT_RECOMMENDED_TOP_10));
if (response.statusCode == 200) {
List listTrend = json.decode(response.body) as List;
return listTrend.map((e) =>
ProductModel.fromJson(e)).toList();
} else {
throw Exception("Failed to fetch data");
}
} catch (e) {
throw Exception("No Internet Connection");
}
}
}
ProductDrugModel
This is how i get the ProductDrugModel object
THe input will be from ProductModel drugbankID
class ProductDrugInfoService {
static Future<List<ProductDrugModel>> getProductDrugInfo(String input) async {
try {
var response =
await http.get(Uri.parse(Constants.PRODUCT_DRUG_INFOR + input));
if (response.statusCode == 200) {
List listTrend = json.decode(response.body) as List;
return listTrend.map((e) => ProductDrugModel.fromJson(e)).toList();
} else {
throw Exception("Failed to fetch data");
}
} catch (e) {
throw Exception("No Internet Connection");
}
}
}
I want to get data from ProductDrugModel by pass the drugbankID to endponit url
then show that data to the UI along with ProductModel
Any suggestion ??
Please help ><

Mapping CSV data in flutter

Auto-complete search list
How to parse csv data instead of json data as mentioned in this article. I am new to csv and I have trouble mappping csv data to a model list. I need to pass the csv list to autocomplete field in another package plz help me in mapping it to the model.
class Players {
String keyword;
int id;
String autocompleteterm;
String country;
Players({
this.keyword,
this.id,
this.autocompleteterm,
this.country
});
factory Players.fromJson(Map<String, dynamic> parsedJson) {
return Players(
keyword: parsedJson['keyword'] as String,
id: parsedJson['id'],
autocompleteterm: parsedJson['autocompleteTerm'] as String,
country: parsedJson['country'] as String
);
}
}
class PlayersViewModel {
static List<Players> players;
static Future loadPlayers() async {
try {
players = new List<Players>();
String jsonString = await rootBundle.loadString('assets/players.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['players'] as List;
for (int i = 0; i < categoryJson.length; i++) {
players.add(new Players.fromJson(categoryJson[i]));
}
} catch (e) {
print(e);
}
}

Flutter: Transferring items from one list into a different list

i have one List (growable) with an item (actually item 0:
items is of class Team
items[_id = 1, _team = "Team01", _note = "blabla"]
and I want to transfer it into another list with a different structure:
participants is of class User
participants[id = 1, name = "participant1"]
skipping the note and translating _id into id and so on.So at last the result would give me
participants[id = 1, name = "team01"]
(sorry for the writing, I describe it out of the debugger)
i tried something like this, but doesnt work with value:
List<TestTeam> participants;
for (var value in items) {
participants.add(new TestTeam(value.id, value.team));
}
my class Team is defined like this:
class Team {
int _id;
String _team;
String _note;
Team(this._team, this._note);
Team.map(dynamic obj) {
this._id = obj['id'];
this._team = obj['team'];
this._note = obj['note'];
}
int get id => _id;
String get team => _team;
String get note => _note;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
if (_id != null) {
map['id'] = _id;
}
map['team'] = _team;
map['note'] = _note;
return map;
}
Team.fromMap(Map<String, dynamic> map) {
this._id = map['id'];
this._team = map['team'];
this._note = map['note'];
}
}
You should implement below way
void main() {
List<Team> teams=[];
List<User> participants=[];
for (var i = 0; i < 4; i++) {
teams.add(Team(i,'Team_$i','Note_$i'));
}
for (var value in teams){
participants.add(User(value.id,value.team));
}
for (var value in teams){
print(value.toString());
}
for (var value in participants){
print(value.toString());
}
}
class Team{
int id;
String team;
String note;
Team(this.id,this.team,this.note);
toString()=> 'Team Map :{id:$id,team:$team,note:$note}';
}
class User{
int id;
String team;
User(this.id,this.team);
toString()=> 'User Map :{id:$id,team:$team}';
}
Output
Team Map :{id:0,team:Team_0,note:Note_0}
Team Map :{id:1,team:Team_1,note:Note_1}
Team Map :{id:2,team:Team_2,note:Note_2}
Team Map :{id:3,team:Team_3,note:Note_3}
User Map :{id:0,team:Team_0}
User Map :{id:1,team:Team_1}
User Map :{id:2,team:Team_2}
User Map :{id:3,team:Team_3}

How to Adding New Data into JSON Dart?

I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}

How to insert a List<Class> into a Map<String, dynamic> in dart?

My problem is that I have a list of the following class:
class ingreso_Egreso_Dummy{
int tipo;
String monto;
String moneda;
String descripcion;
}
then I want to insert the data into a Map which later will be converted into a json and which I am creating like this:
Map<String, dynamic> body;
body = {
"Cod_Prom": "01",
"CodCli": "003526",
"Status": _index_status.toString(),
"NOMBRE": controller_nombre.text,
"APELLIDOS": controller_apellidos.text,
"solicitud":[{
"Cod_Solicit": 1.toString(),
"Fecha": DateFormat("y-d-M").format(DateTime.now()),
"Status_Solicit": "E",}],
"prestamo":[{
"Monto_Solicit":controller_monto_solic.text,
"Plazo":controller_plazo.text,
"Cod_TipoPlazo":_index_tipoplazo.toString(),
"Nombre_Resp":controller_nombreresp.text,
"Telf_Resp":controller_telefonoresp.text,}],
"Ingresos": [{
//// here I want create a loop that returns a map for each value
//// of the list like this:
//// "Descripcion": Listaingresos[i].descripcion;
})
}]
};
Every help is very appreciated, thank you.
// camelCaseStyle is a standard for class names for Dart
class IngresoEgresoDummy {
int tipo;
String monto;
String moneda;
String descripcion;
Map<String, dynamic> toJson(){
return {
'tipo': tipo,
'monto': monto,
'monedo': moneda,
'descripcion': descripcion
};
}
}
and after that
List<IngresoEgresoDummy> listaingresos= List();
Map<String, dynamic> body = {
// all your params
"Ingresos": listaingresos.map((ingreso) => ingreso.toJson()).toList()
// all your params
};