How can i deserialize my json in Flutter/dart - json

I'm quite new to flutter and right now i'm stucked in desterilize the json string into my class.
Appreciate your help on this.
This is my json
[
{
"itemno": "4800888136473",
"itemname": "AXE DEO AFRICA 150ML",
},
{
"itemno": "4800888141125",
"itemname": "AXE DEO BODYSPRAY DARK TMPTTN 150ML",
}
]
And my JSON Class
class ListItemList{
ListItemList({
this.itemno,
this.itemname,
});
String itemno;
String itemname;
factory ListItemList.fromJson(Map<String, dynamic> json) =>
ListItemList(
itemno: json["itemno"],
itemname: json["itemname"],
);
}
How i call
List<ListItemList> result =
ListItemList.fromJson(jsonDecode(response.body));

Check this link "https://app.quicktype.io/"
And paste your json code left side and add class model name.
for eg.
import 'dart:convert';
List<User> userFromJson(String str) => List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
this.itemno,
this.itemname,
});
String itemno;
String itemname;
factory User.fromJson(Map<String, dynamic> json) => User(
itemno: json["itemno"] == null ? null : json["itemno"],
itemname: json["itemname"] == null ? null : json["itemname"],
);
Map<String, dynamic> toJson() => {
"itemno": itemno == null ? null : itemno,
"itemname": itemname == null ? null : itemname,
};
}
//Add below code in service
static Future<List<User>> getUsers() async {
List<User> users = usersFromJson(response.body));
return users;
}
// call service in specific page
List _users;
#override
void initState() {
super.initState();
ApiService.getUsers().then((value) {
setState(() {
_users = value;
});
})
}

Use map to iterate over the JSON which is a list.
final List<ListItemList> result = (jsonDecode(response.body) as List)
.map((e) => ListItemList.fromJson(e))
.toList();

Go to this URL and paste your JSON. It will convert it to both fromJson (json to dart object conversion) and toJson (dart object to json conversion) function.
Here is as example of fromJson and toJosn according to the Json you provided
class List {
List<Items> items;
List({this.items});
List.fromJson(Map<String, dynamic> json) {
if (json['items'] != null) {
items = new List<Items>();
json['items'].forEach((v) {
items.add(new Items.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.items != null) {
data['items'] = this.items.map((v) => v.toJson()).toList();
}
return data;
}
}
class Items {
String itemno;
String itemname;
Items({this.itemno, this.itemname});
Items.fromJson(Map<String, dynamic> json) {
itemno = json['itemno'];
itemname = json['itemname'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['itemno'] = this.itemno;
data['itemname'] = this.itemname;
return data;
}
}

As i mentioned it is a list. Deal with list like;
List<ListItemList> result;
var a = jsonDecode(response.body);
// I can not compile this part you can check syntax
a.forEach((element)
at= ListItemList.fromJson(element);
result.add(at);
);

Related

The class 'List' doesn't have a constructor named 'fromJson'. Try invoking a different constructor, or define a constructor named 'fromJson'

class Product {
String status;
List<List> note;
List<List> table;
Product({this.status, this.note, this.table});
Product.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['note'] != null) {
note = <List>[];
json['note'].forEach((v) { note.add(new List.fromJson(v)); });
}
if (json['table'] != null) {
table = <List>[];
json['table'].forEach((v) { table.add(new List.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.note != null) {
data['note'] = this.note.map((v) => v.toJson()).toList();
}
if (this.table != null) {
data['table'] = this.table.map((v) => v.toJson()).toList();
}
return data;
}
}
The class 'List' doesn't have a constructor named 'fromJson'.
Try invoking a different constructor, or define a constructor named 'fromJson'. / Error in List.fromJson and v.toJson
The error message says it pretty straightforward.
you can not call
new List.fromJson(v)
Try to create a dart Iterable from your json and use .from() constructor
List<E>.from(
Iterable elements,
{bool growable = true}
)
Or try other constructors defined by the List Class https://api.dart.dev/stable/2.14.2/dart-core/List-class.html
This lib might also be helpful
https://pub.dev/packages/json_serializable
The list is an abstract class. It has not a constructor fromJson. If you want to convert from JSON into list, you must assign a list with Elements (Note) Like:
//Generic form
List<E>
// For note
List<Note> note;
// call like that
json['note'].forEach((v) { note.add(new Note.fromJson(v)); });
Model class of Note:
class Note {
String title;
String description;
Note({this.title, this.description});
Note.fromJson(Map<String, dynamic> json) {
title = json['title'];
description = json['description'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
data['description'] = this.description;
return data;
}
}

From json method in subclasses

I have a base class like:
class TransportationVehicle {
String name;
TransportationVehicle(this.name);
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
return data;
}
}
And multiple sub-classes like:
class Bike extends TransportationVehicle {
int pedals;
Bike(String name, this.pedals) : super(name);
#override
Map<String, dynamic> toJson() {
final data = super.toJson();
data['pedals'] = pedals;
return data;
}
}
With that, I can transform a list of different types into a json string. But how would that work with fromJson functionality?
You can use the same idea from the toJson() method by using the base class.
import 'dart:convert';
class TransportationVehicle {
final String? name;
TransportationVehicle({
this.name,
});
factory TransportationVehicle.fromRawJson(String str) =>
TransportationVehicle.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory TransportationVehicle.fromJson(dynamic json) => TransportationVehicle(
name: json['name'] == null ? null : json['name'] as String,
);
Map<String, dynamic> toJson() => {
'name': name == null ? null : name,
};
}
class Bike extends TransportationVehicle {
final int? pedals;
Bike({
String? name,
this.pedals,
}) : super(name: name);
factory Bike.fromRawJson(String str) => Bike.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Bike.fromJson(dynamic json) {
TransportationVehicle vehicle = TransportationVehicle.fromJson(json);
return Bike(
name: vehicle.name == null ? null : vehicle.name,
pedals: json['pedals'] == null ? null : json['pedals'] as int,
);
}
Map<String, dynamic> toJson() {
final data = super.toJson();
data['pedals'] = pedals == null ? null : pedals;
return data;
}
}

Flutter error: the argument type 'dynamic' can't be assigned to the parameter type 'Iterable<dynamic>'

Kindly assist.
I am attempting to create a model using the JSON to Dart tool https://app.quicktype.io/
The aim is to retrieve a list of all companies (with their properties) from a JSON API.
I am getting the below errors:
the argument type 'dynamic' can't be assigned to the parameter type Map<String, dynamic>
the argument type 'dynamic' can't be assigned to the parameter type Iterable
the argument type 'dynamic' can't be assigned to the parameter type Int
Please refer to the image below.
the argument type 'dynamic' can't be assigned to the parameter type...
Thank you.
I have tested this class and it works without errors
import 'dart:convert';
CompanyModel companyModelFromJson(String str) => CompanyModel.fromJson(json.decode(str));
String companyModelToJson(CompanyModel data) => json.encode(data.toJson());
class CompanyModel {
CompanyModel({
this.companies,
});
List<Company> companies;
factory CompanyModel.fromJson(Map<String, dynamic> json) => CompanyModel(
companies: List<Company>.from(json["companies"].map((x) => Company.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"companies": List<dynamic>.from(companies.map((x) => x.toJson())),
};
}
class Company {
Company({
this.id,
this.name,
});
int id;
String name;
factory Company.fromJson(Map<String, dynamic> json) => Company(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
As alternative you can use this code from JsonToDart
class CompanyModel {
List<Companies> companies;
CompanyModel({this.companies});
CompanyModel.fromJson(Map<String, dynamic> json) {
if (json['companies'] != null) {
companies = new List<Companies>();
json['companies'].forEach((v) {
companies.add(new Companies.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.companies != null) {
data['companies'] = this.companies.map((v) => v.toJson()).toList();
}
return data;
}
}
class Companies {
int id;
String name;
Companies({this.id, this.name});
Companies.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}

Dart: converting _InternalLinkedHashMap<dynamic, dynamic> in constructor fails

I am new to Dart and trying to deserialize some json, but I can't quite figure out the trick.
I am able to cast the Map in main as shown, but the commented code does not work and I can't figure out why. I feel like there must be an easier way to do this (outside of using a package for code generation), but I'm not sure what that is.
import 'dart:convert';
import 'dart:io';
class Book {
final String title;
final String path;
Book(this.title, this.path);
Book.fromJson(Map<String, dynamic> content)
: title = content['title'],
path = content['path'];
Map<String, dynamic> toJson() =>
{
'title': title,
'path': path,
};
String toString() {
return '{ title: $title, path: $path }';
}
}
class Books {
final Map<String, Book> bookList;
Books(this.bookList);
// Books.fromJson(Map<String, dynamic> content)
// : bookList = Map<String, Book>.from(jsonDecode(jsonDecode(content)['books']).map((k,v) => MapEntry(k as String, Book.fromJson(v))));
Map<String, dynamic> toJson() =>
{
'books': jsonEncode(bookList),
};
String toString() {
return bookList.toString();
}
}
void main() {
Map<String, Book> bookList = {
"foo": Book("Foo", "/foo"),
"bar": Book("Bar", "/bar"),
};
Books books = Books(bookList);
print(books);
String content = jsonEncode(books);
print(content);
// print(Books.fromJson(jsonDecode(content)));
Map<String, Book> m = Map<String, Book>.from(jsonDecode(jsonDecode(content)['books']).map((k,v) => MapEntry(k as String, Book.fromJson(v))));
print(m);
}
Oops, I needed to remove an invocation of jsonDecode from Books.fromJson...
Books.fromJson(Map<String, dynamic> content)
: bookList = Map<String, Book>.from(jsonDecode((content)['books']).map((k,v) => MapEntry(k as String, Book.fromJson(v))));

How to associate the json data to flutter list?

I am able to fetch the json data in flutter applicaion.
Now I want to associate that data with the List.
How should I do that?
List companydetails;
var jsonResponse = json.decode(response.body);
JSON DATA
{"error":"false","content":[
{
"id":"22","name":"Johnny",},
{"id":"23","name":"Maria",},
]
}
I need to build a list view in flutter from the fetched data.
You can use this model:
class CompanyDetail {
String error;
List<Content> content;
CompanyDetail({this.error, this.content});
CompanyDetail.fromJson(Map<String, dynamic> json) {
error = json['error'];
if (json['content'] != null) {
content = new List<Content>();
json['content'].forEach((v) {
content.add(new Content.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
if (this.content != null) {
data['content'] = this.content.map((v) => v.toJson()).toList();
}
return data;
}
}
class Content {
String id;
String name;
Content({this.id, this.name});
Content.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Then bind the Json data:
var companyDetail = CompanyDetail.fromJson(json.decode(response.body));
Now use Content List in your ListView widget:
companyDetail.content
Example (make sure that content is not null):
....
ListView.builder
(
itemCount: companyDetail.content.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(companyDetail.content[index]);
}
),
...