I have array of country json objects like this
[{"id":4,"name":"Afghanistan","alpha2":"af","alpha3":"afg"},
{"id":8,"name":"Albania","alpha2":"al","alpha3":"alb"},
{"id":12,"name":"Algeria","alpha2":"dz","alpha3":"dza"},..
I have got them to a map like this
Map<String, dynamic> jsonMap;
jsonMap = json.decode(jsonString);
After this I have the data like this
[{id: 4, name: Afghanistan, alpha2: af, alpha3: afg}, {id: 8, name: Albania, alpha2: al, alpha3: alb}, ...
What i want to do is create a List of county objects from this
Country
{
int id;
String name;
String alpha2;
String alpha3;
}
Can anyone explain how to do this conversion ?
The best way to do it is to make a PODO out of this,
class Country {
int id;
String name;
String alpha2;
String alpha3;
Country({this.id, this.name, this.alpha2, this.alpha3});
Country.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
alpha2 = json['alpha2'];
alpha3 = json['alpha3'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['alpha2'] = this.alpha2;
data['alpha3'] = this.alpha3;
return data;
}
}
Now using this you can access the fromJson method and also use the toJson method.
I use this straight forward way:
List<TestModel> myTestModel;
var response = await http.get("myTestUrl");
myTestModel=(json.decode(response.body) as List).map((i) =>
TestModel.fromJson(i)).toList();
The link can be really helpful:
json_serializable
Related
the app.quicktype.io cannot convert.
they are converting and skip the digit class name
class ScoreCardModel {
bool? status;
String? msg;
Data? data;
ScoreCardModel({this.status, this.msg, this.data});
ScoreCardModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
msg = json['msg'];
data = json['data'] = Data.fromJson(json['data']);
}
}
class Data {
String? result;
Scorecard? scorecard;
Data({this.result, this.scorecard});
Data.fromJson(Map<String, dynamic> json) {
result = json['result'];
scorecard = json['scorecard'] != null
? Scorecard.fromJson(json['scorecard'])
: null;
}
}
the quicktype cannot work with digits, I don't know why is this. I think they are in the developing stage. I Have the answer. I'm looking for the correct answer.
You can use https://jsontodart.com/, They are just including digit as model(Class) name. But You have to rename the model name like follows,
class 1 {
String score;
String wicket;
String ball;
1({this.score, this.wicket, this.ball});
1.fromJson(Map<String, dynamic> json) {
score = json['score'];
wicket = json['wicket'];
ball = json['ball'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['score'] = this.score;
data['wicket'] = this.wicket;
data['ball'] = this.ball;
return data;
}
}
to
class teamA {
String score;
String wicket;
String ball;
teamA({this.score, this.wicket, this.ball});
teamA.fromJson(Map<String, dynamic> json) {
score = json['score'];
wicket = json['wicket'];
ball = json['ball'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['score'] = this.score;
data['wicket'] = this.wicket;
data['ball'] = this.ball;
return data;
}
}
This is the parent which has an implemented method
abstract class CommonModel {
int id;
String name;
....
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Id'] = this.id;
data['Name'] = this.name;
return data;
}
}
and this the the child class which i need to use the method [toJson] on it with its implementation and add more data.
import 'package:Elnota/models/governorate.dart';
import 'package:Elnota/models/abstract_common_model.dart';
class Centeral extends CommonModel{
Governorate gov;
Centeral({
int id,
String name,
this.gov}) : super(id:id, name:name);
Centeral.fromJson(Map<String, dynamic> json) :super.fromJson(json){
gov = json['Gov'] != null ? new Governorate.fromJson(json['Gov']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Gov'] = this.gov;
}
}
It's a little hard to understand what you need, but how about this:
#override
Map<String, dynamic> toJson() {
final data = super.toJson();
data['Gov'] = gov.toJson();
return data;
}
I am new to both Flutter and Dart and trying to convert some android studio application to use flutter if I can. I am trying to parse some simple json to learn how all of the dart/flutter features can help me.
The class structure that I want to write to is:
class Company extends Salinas {
final String name;
Company({this.name}) : super();
factory Company.fromJson(Map<String, dynamic> json) => _$CompanyFromJson(json);
Map<String, dynamic> toJson() => _$CompanyToJson(this);
}
class Salinas {
final int id;
Salinas({this.id});
factory Salinas.fromJson(Map<String, dynamic> json) => _$SalinasFromJson(json);
Map<String, dynamic> toJson() => _$SalinasToJson(this);
}
the json string is simple
{"id":1,"name":"Acme"}
and:
print(company.id)is null
print(company.name) is Acme;
when I look at the Company.g.dart file there is no reference to the extended class Salinas?
is there a way to do this?
I'm clearly missing something.
You need to define extended class properties in child constructor like this:
class Company extends Salinas {
final String name;
Company({id, this.name}) : super(id: id);
}
After you will see this result:
print(company.id) is 1
print(company.name) is Acme;
class Company {
int id;
String name;
Company({this.id, this.name});
Company.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;
}
}
On the basis of JSON you have provided, you should have made a Model as above.
After that, you can map the whole thing quite conveniently,
Company company = Company.fromJson(response);
and then you are free to print
print(company.id);
print(company.name);
My list is too long. So, I encode and save it to the database. I want to decode it. How do I do it?
encode way,
String shoppingCartToJson(List<ShoppingCartModel> data) => jsonEncode(data.map((i) => i.toMap()).toList()).toString();
How to decode?
I tried, but return type is String not List of object
List<ShoppingCartModel> shoppingFromJson(String str) => jsonDecode(str);
In your ShoppingCartModel class you should have functions to encode and decode, to the type and from dynamic respectively.
So your ShoppingCartModel class should look like (assuming the parameters inside the class):
class ShoppingCartModel {
String itemId;
String itemName;
double quantity;
ShoppingCartModel.fromJson(Map<String, dynamic> json) {
if (json == null) return;
itemId = json['item_id'];
itemName = json['item_name'];
quantity = json['quantity'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['item_id'] = this.itemId;
data['item_name'] = this.itemName;
data['quantity'] = this.quantity;
return data;
}
}
And then you can encode and decode using:
Encode:
json.encode(data);
Decode:
List<dynamic> decodedData = json.decode(strData);
List<ShoppingCartModel> dataDecodedList = List<ShoppingCartModel>.from(
dataDecoded.map((x) => ShoppingCartModel.fromJson(x)),
);
I have string like this,
{id:1, name: lorem ipsum, address: dolor set amet}
And I need to convert that string to json, how I can do it in dart flutter? thank you so much for your help.
You have to use json.decode. It takes in a json object and let you handle the nested key value pairs. I'll write you an example
import 'dart:convert';
// actual data sent is {success: true, data:{token:'token'}}
final response = await client.post(url, body: reqBody);
// Notice how you have to call body from the response if you are using http to retrieve json
final body = json.decode(response.body);
// This is how you get success value out of the actual json
if (body['success']) {
//Token is nested inside data field so it goes one deeper.
final String token = body['data']['token'];
return {"success": true, "token": token};
}
Create a model class
class User {
int? id;
String? name;
String? address;
User({this.id, this.name, this.address});
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
address = json['address'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['address'] = this.address;
return data;
}
}
In the logic section
String data ='{id:1, name: lorem ipsum, address: dolor set amet}';
var encodedString = jsonEncode(data);
Map<String, dynamic> valueMap = json.decode(encodedString);
User user = User.fromJson(valueMap);
Also need to import
import 'dart:convert';
You can also convert JSON array to list of Objects as following:
String jsonStr = yourMethodThatReturnsJsonText();
Map<String,dynamic> d = json.decode(jsonStr.trim());
List<MyModel> list = List<MyModel>.from(d['jsonArrayName'].map((x) => MyModel.fromJson(x)));
And MyModel is something like this:
class MyModel{
String name;
int age;
MyModel({this.name,this.age});
MyModel.fromJson(Map<String, dynamic> json) {
name= json['name'];
age= json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
return data;
}
}
String name = "{click_action: FLUTTER_NOTIFICATION_CLICK, sendByImage: https://ujjwalchef.staging-server.in/uploads/users/1636620532.png, status: done, sendByName: mohittttt, id: HM11}";
List<String> str = name.replaceAll("{","").replaceAll("}","").split(",");
Map<String,dynamic> result = {};
for(int i=0;i<str.length;i++){
List<String> s = str[i].split(":");
result.putIfAbsent(s[0].trim(), () => s[1].trim());
}
print(result);
}
You must need to use this sometimes
Map<String, dynamic> toJson() {
return {
jsonEncode("phone"): jsonEncode(numberPhone),
jsonEncode("country"): jsonEncode(country),
};
}
This code give you a like string {"numberPhone":"+225657869", "country":"CI"}. So it's easy to decode it's after like that
json.decode({"numberPhone":"+22565786589", "country":"CI"})
You must import dart:encode libary. Then use the jsonDecode function, that will produce a dynamic similar to a Map
https://api.dartlang.org/stable/2.2.0/dart-convert/dart-convert-library.html
For converting string to JSON we have to modify it with custom logic, in here first we remove all symbols of array and object and then we split text with special characters and append with key and value(for map).
Please try this code snippet in dartpad.dev
import 'dart:developer';
void main() {
String stringJson = '[{product_id: 1, quantity: 1, price: 16.5}]';
stringJson = removeJsonAndArray(stringJson);
var dataSp = stringJson.split(',');
Map<String, String> mapData = {};
for (var element in dataSp) {
mapData[element.split(':')[0].trim()] = element.split(':')[1].trim();
}
print("jsonInModel: ${DemoModel.fromJson(mapData).toJson()}");
}
String removeJsonAndArray(String text) {
if (text.startsWith('[') || text.startsWith('{')) {
text = text.substring(1, text.length - 1);
if (text.startsWith('[') || text.startsWith('{')) {
text = removeJsonAndArray(text);
}
}
return text;
}
class DemoModel {
String? productId;
String? quantity;
String? price;
DemoModel({this.productId, this.quantity, this.price});
DemoModel.fromJson(Map<String, dynamic> json) {
log('json: ${json['product_id']}');
productId = json['product_id'];
quantity = json['quantity'];
price = json['price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['product_id'] = productId;
data['quantity'] = quantity;
data['price'] = price;
return data;
}
}