我最近開始了我的 Flutter(Dart) 之旅。我正在嘗試構建一個使用 API 呼叫獲取一些 JSON 資訊的應用程式。
我已成功為以下 JSON 檔案撰寫了代碼
[
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "Smoor Chocolates Lounge",
"pl2_api": "Vasant Nagar",
"dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
"dl2_api": "Cunningham Road, Bengaluru - 560052",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "0123456789",
"eid_api": "[email protected]"
},
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "Smoor Chocolates Lounge",
"pl2_api": "Vasant Nagar",
"dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
"dl2_api": "Cunningham Road, Bengaluru - 560052",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "0123456789",
"eid_api": "[email protected]"
},
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "Smoor Chocolates Lounge",
"pl2_api": "Vasant Nagar",
"dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
"dl2_api": "Cunningham Road, Bengaluru - 560052",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "0123456789",
"eid_api": "[email protected]"
},
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "Smoor Chocolates Lounge",
"pl2_api": "Vasant Nagar",
"dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
"dl2_api": "Cunningham Road, Bengaluru - 560052",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "0123456789",
"eid_api": "[email protected]"
},
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "Smoor Chocolates Lounge",
"pl2_api": "Vasant Nagar",
"dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
"dl2_api": "Cunningham Road, Bengaluru - 560052",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "0123456789",
"eid_api": "[email protected]"
}
]
這是它的元素類
class Element {
Element({
this.onApi,
this.tlApi,
this.pl1Api,
this.pl2Api,
this.dl1Api,
this.dl2Api,
this.fnApi,
this.lnApi,
this.cnApi,
this.eidApi,
});
String onApi;
String tlApi;
String pl1Api;
String pl2Api;
String dl1Api;
String dl2Api;
String fnApi;
String lnApi;
String cnApi;
String eidApi;
factory Element.fromJson(Map<String, dynamic> json) => Element(
onApi: json["order_number"],
tlApi: json["tl_api"],
pl1Api: json["pl1_api"],
pl2Api: json["pl2_api"],
dl1Api: json["dl1_api"],
dl2Api: json["dl2_api"],
fnApi: json["fn_api"],
lnApi: json["ln_api"],
cnApi: json["cn_api"],
eidApi: json["eid_api"],
);
}
這是它的api呼叫代碼
import 'dart:convert';
import 'package:http/http.dart';
import 'package:smoorapplication/src/constants/constants.dart';
import 'package:smoorapplication/src/model/elements.dart';
Future<List<Element>> apiGetOrder() async{
var response = await get(Uri.parse(MOCK_API_SMOOR_1));
var jsonData = jsonDecode(response.body);
List<Element> elements = <Element>[];
for(var i in jsonData){
Element element = Element.fromJson(i);
elements.add(element);
}
print(elements.length);
}
我想要這種凌亂的JSON檔案的api呼叫代碼和元素類代碼
{
"orders": [
{
"id": 3927180738697,
"admin_graphql_api_id": "gid://shopify/Order/00000",
"app_id": 580111,
"browser_ip": "122.172.179.207",
"buyer_accepts_marketing": false,
"cancel_reason": null,
"cancelled_at": null,
"cart_token": null,
"checkout_id": 20726986440841,
"checkout_token": "65651fdv561165",
"client_details": {
"accept_language": "en-US,en;q=0.9",
"browser_height": 860,
"browser_ip": "122.172.179.207",
"browser_width": 1487,
"session_hash": null,
},
"closed_at": null,
"confirmed": true,
"contact_email": null,
"created_at": "2021-12-16T11:03:59 05:30",
"currency": "INR",
"current_subtotal_price": "500.00",
"current_subtotal_price_set": {
"shop_money": {
"amount": "500.00",
"currency_code": "INR"
},
"presentment_money": {
"amount": "500.00",
"currency_code": "INR"
}
},
"current_total_discounts": "0.00",
"current_total_discounts_set": {
"shop_money": {
"amount": "0.00",
"currency_code": "INR"
},
"presentment_money": {
"amount": "0.00",
"currency_code": "INR"
}
},
"current_total_duties_set": null,
"current_total_price": "600.00",
"current_total_price_set": {
"shop_money": {
"amount": "600.00",
"currency_code": "INR"
},
"presentment_money": {
"amount": "600.00",
"currency_code": "INR"
}
},
"current_total_tax": "91.52",
"current_total_tax_set": {
"shop_money": {
"amount": "91.52",
"currency_code": "INR"
},
"presentment_money": {
"amount": "91.52",
"currency_code": "INR"
}
}
}
]
}
uj5u.com熱心網友回復:
呼叫API你的方法就足夠了,你只需要return根據函式的回傳型別從函式中取值。在您的函式中,您有一種return型別,List<Element>因此您需要對代碼進行一些更改
Future<List<Element>> apiGetOrder() async{
var response = await get(Uri.parse(MOCK_API_SMOOR_1));
var jsonData = jsonDecode(response.body)["orders"];
List<Element> elements = <Element>[];
for(var i in jsonData){
Element element = Element.fromJson(i);
elements.add(element);
}
print(elements.length);
return elements; // returning value
}
并class根據response你可以使用一個方便的工具來創建一個Quicktype我也在分享相同的鏈接
https://app.quicktype.io/
uj5u.com熱心網友回復:
我猜你可以想出一個 API 呼叫方法(類似于你已經做過的)。您提供的 JSON 具有不同的子級別。所以,你可以為它使用不同的類。為簡化起見,有一些工具可以將 JSON 轉換為 Dart。你可以去找他們。一旦這樣的工具是這個。
API 呼叫很可能只是將其添加到根元素中。我想它應該照顧其余的。(因為JSON轉dart的時候也包含了inter依賴類)
我試圖轉換你的 JSON(在第 19 行有一個額外的逗號),下面是我得到的結果。
class Element {
List<Orders> orders;
Element({this.orders});
Element.fromJson(Map<String, dynamic> json) {
if (json['orders'] != null) {
orders = new List<Orders>();
json['orders'].forEach((v) {
orders.add(new Orders.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.orders != null) {
data['orders'] = this.orders.map((v) => v.toJson()).toList();
}
return data;
}
}
class Orders {
int id;
String adminGraphqlApiId;
int appId;
String browserIp;
bool buyerAcceptsMarketing;
Null cancelReason;
Null cancelledAt;
Null cartToken;
int checkoutId;
String checkoutToken;
ClientDetails clientDetails;
Null closedAt;
bool confirmed;
Null contactEmail;
String createdAt;
String currency;
String currentSubtotalPrice;
CurrentSubtotalPriceSet currentSubtotalPriceSet;
String currentTotalDiscounts;
CurrentSubtotalPriceSet currentTotalDiscountsSet;
Null currentTotalDutiesSet;
String currentTotalPrice;
CurrentSubtotalPriceSet currentTotalPriceSet;
String currentTotalTax;
CurrentSubtotalPriceSet currentTotalTaxSet;
Orders(
{this.id,
this.adminGraphqlApiId,
this.appId,
this.browserIp,
this.buyerAcceptsMarketing,
this.cancelReason,
this.cancelledAt,
this.cartToken,
this.checkoutId,
this.checkoutToken,
this.clientDetails,
this.closedAt,
this.confirmed,
this.contactEmail,
this.createdAt,
this.currency,
this.currentSubtotalPrice,
this.currentSubtotalPriceSet,
this.currentTotalDiscounts,
this.currentTotalDiscountsSet,
this.currentTotalDutiesSet,
this.currentTotalPrice,
this.currentTotalPriceSet,
this.currentTotalTax,
this.currentTotalTaxSet});
Orders.fromJson(Map<String, dynamic> json) {
id = json['id'];
adminGraphqlApiId = json['admin_graphql_api_id'];
appId = json['app_id'];
browserIp = json['browser_ip'];
buyerAcceptsMarketing = json['buyer_accepts_marketing'];
cancelReason = json['cancel_reason'];
cancelledAt = json['cancelled_at'];
cartToken = json['cart_token'];
checkoutId = json['checkout_id'];
checkoutToken = json['checkout_token'];
clientDetails = json['client_details'] != null
? new ClientDetails.fromJson(json['client_details'])
: null;
closedAt = json['closed_at'];
confirmed = json['confirmed'];
contactEmail = json['contact_email'];
createdAt = json['created_at'];
currency = json['currency'];
currentSubtotalPrice = json['current_subtotal_price'];
currentSubtotalPriceSet = json['current_subtotal_price_set'] != null
? new CurrentSubtotalPriceSet.fromJson(
json['current_subtotal_price_set'])
: null;
currentTotalDiscounts = json['current_total_discounts'];
currentTotalDiscountsSet = json['current_total_discounts_set'] != null
? new CurrentSubtotalPriceSet.fromJson(
json['current_total_discounts_set'])
: null;
currentTotalDutiesSet = json['current_total_duties_set'];
currentTotalPrice = json['current_total_price'];
currentTotalPriceSet = json['current_total_price_set'] != null
? new CurrentSubtotalPriceSet.fromJson(json['current_total_price_set'])
: null;
currentTotalTax = json['current_total_tax'];
currentTotalTaxSet = json['current_total_tax_set'] != null
? new CurrentSubtotalPriceSet.fromJson(json['current_total_tax_set'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['admin_graphql_api_id'] = this.adminGraphqlApiId;
data['app_id'] = this.appId;
data['browser_ip'] = this.browserIp;
data['buyer_accepts_marketing'] = this.buyerAcceptsMarketing;
data['cancel_reason'] = this.cancelReason;
data['cancelled_at'] = this.cancelledAt;
data['cart_token'] = this.cartToken;
data['checkout_id'] = this.checkoutId;
data['checkout_token'] = this.checkoutToken;
if (this.clientDetails != null) {
data['client_details'] = this.clientDetails.toJson();
}
data['closed_at'] = this.closedAt;
data['confirmed'] = this.confirmed;
data['contact_email'] = this.contactEmail;
data['created_at'] = this.createdAt;
data['currency'] = this.currency;
data['current_subtotal_price'] = this.currentSubtotalPrice;
if (this.currentSubtotalPriceSet != null) {
data['current_subtotal_price_set'] =
this.currentSubtotalPriceSet.toJson();
}
data['current_total_discounts'] = this.currentTotalDiscounts;
if (this.currentTotalDiscountsSet != null) {
data['current_total_discounts_set'] =
this.currentTotalDiscountsSet.toJson();
}
data['current_total_duties_set'] = this.currentTotalDutiesSet;
data['current_total_price'] = this.currentTotalPrice;
if (this.currentTotalPriceSet != null) {
data['current_total_price_set'] = this.currentTotalPriceSet.toJson();
}
data['current_total_tax'] = this.currentTotalTax;
if (this.currentTotalTaxSet != null) {
data['current_total_tax_set'] = this.currentTotalTaxSet.toJson();
}
return data;
}
}
class ClientDetails {
String acceptLanguage;
int browserHeight;
String browserIp;
int browserWidth;
Null sessionHash;
ClientDetails(
{this.acceptLanguage,
this.browserHeight,
this.browserIp,
this.browserWidth,
this.sessionHash});
ClientDetails.fromJson(Map<String, dynamic> json) {
acceptLanguage = json['accept_language'];
browserHeight = json['browser_height'];
browserIp = json['browser_ip'];
browserWidth = json['browser_width'];
sessionHash = json['session_hash'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['accept_language'] = this.acceptLanguage;
data['browser_height'] = this.browserHeight;
data['browser_ip'] = this.browserIp;
data['browser_width'] = this.browserWidth;
data['session_hash'] = this.sessionHash;
return data;
}
}
class CurrentSubtotalPriceSet {
ShopMoney shopMoney;
ShopMoney presentmentMoney;
CurrentSubtotalPriceSet({this.shopMoney, this.presentmentMoney});
CurrentSubtotalPriceSet.fromJson(Map<String, dynamic> json) {
shopMoney = json['shop_money'] != null
? new ShopMoney.fromJson(json['shop_money'])
: null;
presentmentMoney = json['presentment_money'] != null
? new ShopMoney.fromJson(json['presentment_money'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.shopMoney != null) {
data['shop_money'] = this.shopMoney.toJson();
}
if (this.presentmentMoney != null) {
data['presentment_money'] = this.presentmentMoney.toJson();
}
return data;
}
}
class ShopMoney {
String amount;
String currencyCode;
ShopMoney({this.amount, this.currencyCode});
ShopMoney.fromJson(Map<String, dynamic> json) {
amount = json['amount'];
currencyCode = json['currency_code'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['amount'] = this.amount;
data['currency_code'] = this.currencyCode;
return data;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382752.html
上一篇:在Dart中async/await/then是如何真正作業的?
下一篇:如何處理空的JSON物件?
