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;
}
}
Related
I'm trying to integrate Google Pay in my Flutter App following this official tutorial from Google:
https://developers.googleblog.com/2021/05/google-pay-introduces-flutter-plugin-for-payments.html
It works so far that I receive the paymentResult that is mentioned at the very end of the tutorial:
// In your Stateless Widget class or State
void onGooglePayResult(paymentResult) {
// Send the resulting Google Pay token to your server or PSP
}
When I log the paymentResult (paymentResult.toString()) it looks like this:
{apiVersion: 2, apiVersionMinor: 0, paymentMethodData: {description: Visa7001, info: {billingAddress: {address1: myStreet 11, address2: , address3: , administrativeArea: , countryCode: DE, locality: myCity, name: myName, phoneNumber: myNumber, postalCode: myCode, sortingCode: }, cardDetails: myDetails, cardNetwork: VISA}, tokenizationData: {token: examplePaymentMethodToken, type: PAYMENT_GATEWAY}, type: CARD}}
This looks good, now I want to parse this response, but it doesn't work with a JSON decoding, because the keys are not in quotation marks (apiVersion instead of "apiVersion").
According to the tutorial I need the token value (=examplePaymentMethodToken), and for my app I also want to access the user information like name and address, so that my user doesn't have to type in everything himself.
What type is the paymentResult if it's not JSON? How can I parse it?
P.S. I know Google did no mistake here, but their tutorial could really be a bit longer...
I'm using the latest pay package: pay: ^1.0.10
UPDATE:
I found a way to transform the paymentResult to a Map, but when I iterate over the Map it never gets to the third entry:
void onGooglePayResult(paymentResult) {
Map<String, dynamic> resMap = Map<String, dynamic>.from(paymentResult);
MyPaymentResult gPay = new MyPaymentResult();
log('resMap entries: ' + resMap.entries.toString());
resMap.entries.forEach((element) {
log("next key: " + element.key);
if (element.key == "apiVersion") {
log("Api Version found: " + element.value.toString());
gPay.apiVersion = element.value;
} else if (element.key == "apiVersionMinor") {
log("apiVersionMinor found: " + element.value.toString());
gPay.apiVersionMinor = element.value;
} else if (element.key == "paymentMethodData") {
log("paymentMethodData found");
}
}
}
The log:
[log] resMap entries: (MapEntry(apiVersion: 2), MapEntry(apiVersionMinor: 0), MapEntry(paymentMethodData: {description: Visa •••• 7001, info: {billingAddress: {address1: ...... }, cardDetails: 7001, cardNetwork: VISA}, tokenizationData: {token: examplePaymentMethodToken, type: PAYMENT_GATEWAY}, type: CARD}))
[log] next key: apiVersion
[log] Api Version found: 2
[log] next key: apiVersionMinor
[log] apiVersionMinor found: 0
The third entry never gets logged, altough it's in the logged Map??
Is there a easier way to convert a map to an Object?
This works, but this can't be the best solution:
void onGooglePayResult(paymentResult) {
log("Received result!! ${paymentResult.toString()}");
Map<String, dynamic> resMap = Map<String, dynamic>.from(paymentResult);
int apiVersion = resMap['apiVersion'];
int apiVersionMinor = resMap['apiVersionMinor'];
Map<String, dynamic> paymentMethodDataMap =
Map<String, dynamic>.from(resMap['paymentMethodData']);
String description = paymentMethodDataMap['description'];
String type = paymentMethodDataMap['type'];
Map<String, dynamic> infoMap =
Map<String, dynamic>.from(paymentMethodDataMap['info']);
String cardDetails = infoMap['cardDetails'];
String cardNetwork = infoMap['cardNetwork'];
Map<String, dynamic> tokenizationDataMap =
Map<String, dynamic>.from(paymentMethodDataMap['tokenizationData']);
String token = tokenizationDataMap['token'];
String tokenType = tokenizationDataMap['type'];
Map<String, dynamic> billingAddressMap =
Map<String, dynamic>.from(infoMap['billingAddress']);
String address1 = billingAddressMap['address1'];
String address2 = billingAddressMap['address2'];
String address3 = billingAddressMap['address3'];
String administrativeArea = billingAddressMap['administrativeArea'];
String countryCode = billingAddressMap['countryCode'].toString();
String locality = billingAddressMap['locality'];
String name = billingAddressMap['name'];
String phoneNumber = billingAddressMap['phoneNumber'];
int postalCode = int.parse(billingAddressMap['postalCode']);
String sortingCode = billingAddressMap['sortingCode'];
BillingAddress billingAddress = new BillingAddress(
address1,
address2,
address3,
administrativeArea,
countryCode,
locality,
name,
phoneNumber,
postalCode,
sortingCode);
GPayInfo gPayInfo =
new GPayInfo(billingAddress, cardDetails, cardNetwork);
GPayTokenizationData tokenizationData =
new GPayTokenizationData(token, tokenType);
PaymentMethodData paymentMethodData =
new PaymentMethodData(description, gPayInfo, tokenizationData);
GooglePayPaymentResult gPay = new GooglePayPaymentResult(
apiVersion, apiVersionMinor, paymentMethodData, type);
log(gPay.paymentMethodData.tokenizationData.token);
}
Resulting log: [log] examplePaymentMethodToken (which is what I was searching for)
I'm sending response.body and country name with slash as like germany/ as parameter and converting it to Germany in parser and returning. But if i use parameter, i'm getting error of the getter 'vacTotal' was called on null. If i write "Germany"to countryDataVac["Germany"] the code works correctly. Is it the problem on {"Global": new CountryDataVac()}? The default value is "Global".
main.dart:
Map<String, CountryDataVac> countryDataVac = {"Global": new CountryDataVac()};
static Map<String, CountryDataVac> getCountryDataVac(String body, var countryname) {
Map<String, CountryDataVac> countryDataVac = {};
responseVac1Day = await http.get("https://disease.sh/v3/covid-19/vaccine/coverage?fullData=true&lastdays=1"); //vaccine number info
countryDataVac = Parser.getCountryDataVac(responseVac1Day.body, "germany/"); //vaccine number info
Parser.dart:
var usera = CountryDataVac.fromJson(jsonDecode(result));
countryDataVac[capitalize(countryname).replaceAll("/", "")] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //gives 'germany/' as 'Germany' but getting error if i get the countryname by parameter
countryDataVac["Germany"] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //works
}
CountryDataVac.dart (created by json to dart)
import 'dart:convert';
List<CountryDataVac> countryDataVacFromJson(String str) => List<CountryDataVac>.from(json.decode(str).map((x) => CountryDataVac.fromJson(x)));
String countryDataVacToJson(List<CountryDataVac> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountryDataVac {
CountryDataVac({
this.vacTotal = 0,
this.vacDaily = 0,
this.vactotalPerHundred = 0,
this.vacdailyPerMillion = 0,
this.date = "",
});
int vacTotal = 0;
int vacDaily = 0;
int vactotalPerHundred = 0;
int vacdailyPerMillion = 0;
String date = "";
factory CountryDataVac.fromJson(Map<String, dynamic> json) => CountryDataVac(
vacTotal: json["total"],
vacDaily: json["daily"],
vactotalPerHundred: json["totalPerHundred"],
vacdailyPerMillion: json["dailyPerMillion"],
date: json["date"],
);
Map<String, dynamic> toJson() => {
"total": vacTotal,
"daily": vacDaily,
"totalPerHundred": vactotalPerHundred,
"dailyPerMillion": vacdailyPerMillion,
"date": date,
};
}
use
countryname.replaceFirst(countryname[0], countryname[0].toUpperCase()).replaceAll("/", "");
instead of
capitalize(countryname).replaceAll("/", "")
i think there is something wrong with your capitalize method
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);
}
}
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
};
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;
}