[英]Flutter : Json parsing
我正在尝试解析 Flutter 中的 API 响应。 API 响应如下所示。 如何在 Flutter 中解析相同的内容? 我想解析所有的值。
parsedJson
在参数fromJson
方法具有所有的值。 我确定我在解析方面做错了。
非常感谢您的帮助! 提前致谢。
{
"responseModel": {
"data": [
{
"offers": {
"brandName": "Yoga",
"brandLogo": "364t3.jpg",
"id": 2214,
"title": "Up to 40% discount on yoga classes",
"shortDescription": "<p>Up to 40% discount </p>",
"categories": null,
"subcategories": null,
"offerContactAddress": "<p>Kolkata</p>",
"offerContactWebsite": "http://www.google.com",
"offerContactTelephone": "123 456",
"offerContactEmail": "abcd@gmail.com",
"offerContactMobileNumber": null,
"aboutThisOffer": "<p>Yoga is a science of healthy and happy living. </p>",
"details": [
{
"type": "OfferValue",
"name": "Offer",
"content": "<p>My Content</p>"
}
],
"locationDetails": [
{
"latitude": "25.32",
"longitude": "55.23",
"address": "Kolkata"
},
{
"latitude": "25.1239",
"longitude": "55.643",
"address": "Mumbai"
}
],
"offerValidity": {
"validFrom": "10/17/2013",
"validTo": "12/31/2020"
},
"keywordList": {
"keywords": [
"Yoga",
"Weight Loss"
]
},
"images": [
"20pic2.jpg",
"20pic1.jpg"
],
"mobileofflineimages": null,
"categoryIds": [
4316
],
"discount": "10",
"isNewOffer": false,
"specialOfferContent": null,
"CreatedDate": "27/05/2018 12:47:42",
"UpdatedDate": "11/12/2019 08:35:55",
"isPreview": false,
"isFeatured": false
},
"Id": 22184,
"CreateDate": "2018-05-27T12:47:42",
"OfferDatefromTo": {
"validFrom": "2013-10-17T00:00:00",
"validTo": "2020-12-31T00:00:00"
},
"IsPreview": false,
"BrandId": 6542,
"CategoryIds": [
4316
],
"UpdatedDate": "2019-12-11T08:35:55",
"NotificationTrackID": "00000000-0000-0000-0000-000000000000",
"NotificationPriority": 0,
"NotificationPriorityOrderName": null,
"ContactAddress": "Address",
"IsPushNotification": false
}
],
"pageheaderdetail": {
"title": null,
"content": null,
"bannerTitle": null,
"bannerImage": null,
"metaTitle": null,
"metaDescription": null,
"metaKeywords": null,
"PageId": null,
"emailAddress": null,
"userId": null,
"preferedName": null
},
"status": 1,
"error": null
}
}
这是我尝试在 OfferModel.fromJson 方法中解析它的方式:
class OfferModel {
_ResponseModel _responseModel;
OfferModel.fromJson(Map<String, dynamic> parsedJson) {
print(parsedJson['responseModel']['data'].length);
_responseModel = parsedJson['responseModel'];
List<_Data> temp = [];
for(int i=0; i < parsedJson['responseModel']['data'].length; i++) {
_Data data = _Data(parsedJson['responseModel']['data']._data[i]);
temp.add(data);
}
_responseModel._data = temp;
print('Responseeeeee= ${_responseModel._data[0]._offer.brandName}');
}
}
class _ResponseModel {
List<_Data> _data = [];
}
class _Offer {
String brandName;
String brandLogo;
String id;
String title;
String shortDescription;
_Offer(offer) {
brandName = offer['brandName'];
brandLogo = offer['brandLogo'];
id = offer['id'];
title = offer['title'];
shortDescription = offer['shortDescription'];
}
}
class _Data {
int id;
String createDate;
_Offer _offer;
_Data(data) {
id = data['Id'];
createDate = data['CreateDate'];
_offer = data['offers'];
}
int get iD => id;
String get create_date => createDate;
}
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_sound_example/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<OfferModel> dataList = List();
bool _isLoading = false;
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadFromAssets();
final youData = offerModelFromJson(jsonString);
dataList.add(youData);
setState(() {
_isLoading = false;
});
}
@override
void initState() {
super.initState();
loadyourData();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return Column(
children: <Widget>[
new Text(dataList[index]
.responseModel
.data[0]
.offers
.brandName),
new Text(dataList[index]
.responseModel
.data[0]
.offers
.details[0]
.name),
new Text(dataList[index].responseModel.status.toString()),
],
);
}),
)),
);
}
}
这是主 ui 页面和数据加载形式您提供的资产 json
// To parse this JSON data, do
//
// final offerModel = offerModelFromJson(jsonString);
import 'dart:convert';
OfferModel offerModelFromJson(String str) =>
OfferModel.fromJson(json.decode(str));
String offerModelToJson(OfferModel data) => json.encode(data.toJson());
class OfferModel {
ResponseModel responseModel;
OfferModel({
this.responseModel,
});
factory OfferModel.fromJson(Map<String, dynamic> json) => OfferModel(
responseModel: ResponseModel.fromJson(json["responseModel"]),
);
Map<String, dynamic> toJson() => {
"responseModel": responseModel.toJson(),
};
}
class ResponseModel {
List<Datum> data;
Pageheaderdetail pageheaderdetail;
int status;
dynamic error;
ResponseModel({
this.data,
this.pageheaderdetail,
this.status,
this.error,
});
factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
pageheaderdetail: Pageheaderdetail.fromJson(json["pageheaderdetail"]),
status: json["status"],
error: json["error"],
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"pageheaderdetail": pageheaderdetail.toJson(),
"status": status,
"error": error,
};
}
class Datum {
Offers offers;
int id;
DateTime createDate;
Offer offerDatefromTo;
bool isPreview;
int brandId;
List<int> categoryIds;
DateTime updatedDate;
String notificationTrackId;
int notificationPriority;
dynamic notificationPriorityOrderName;
String contactAddress;
bool isPushNotification;
Datum({
this.offers,
this.id,
this.createDate,
this.offerDatefromTo,
this.isPreview,
this.brandId,
this.categoryIds,
this.updatedDate,
this.notificationTrackId,
this.notificationPriority,
this.notificationPriorityOrderName,
this.contactAddress,
this.isPushNotification,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
offers: Offers.fromJson(json["offers"]),
id: json["Id"],
createDate: DateTime.parse(json["CreateDate"]),
offerDatefromTo: Offer.fromJson(json["OfferDatefromTo"]),
isPreview: json["IsPreview"],
brandId: json["BrandId"],
categoryIds: List<int>.from(json["CategoryIds"].map((x) => x)),
updatedDate: DateTime.parse(json["UpdatedDate"]),
notificationTrackId: json["NotificationTrackID"],
notificationPriority: json["NotificationPriority"],
notificationPriorityOrderName: json["NotificationPriorityOrderName"],
contactAddress: json["ContactAddress"],
isPushNotification: json["IsPushNotification"],
);
Map<String, dynamic> toJson() => {
"offers": offers.toJson(),
"Id": id,
"CreateDate": createDate.toIso8601String(),
"OfferDatefromTo": offerDatefromTo.toJson(),
"IsPreview": isPreview,
"BrandId": brandId,
"CategoryIds": List<dynamic>.from(categoryIds.map((x) => x)),
"UpdatedDate": updatedDate.toIso8601String(),
"NotificationTrackID": notificationTrackId,
"NotificationPriority": notificationPriority,
"NotificationPriorityOrderName": notificationPriorityOrderName,
"ContactAddress": contactAddress,
"IsPushNotification": isPushNotification,
};
}
class Offer {
String validFrom;
String validTo;
Offer({
this.validFrom,
this.validTo,
});
factory Offer.fromJson(Map<String, dynamic> json) => Offer(
validFrom: json["validFrom"],
validTo: json["validTo"],
);
Map<String, dynamic> toJson() => {
"validFrom": validFrom,
"validTo": validTo,
};
}
class Offers {
String brandName;
String brandLogo;
int id;
String title;
String shortDescription;
dynamic categories;
dynamic subcategories;
String offerContactAddress;
String offerContactWebsite;
String offerContactTelephone;
String offerContactEmail;
dynamic offerContactMobileNumber;
String aboutThisOffer;
List<Detail> details;
List<LocationDetail> locationDetails;
Offer offerValidity;
KeywordList keywordList;
List<String> images;
dynamic mobileofflineimages;
List<int> categoryIds;
String discount;
bool isNewOffer;
dynamic specialOfferContent;
String createdDate;
String updatedDate;
bool isPreview;
bool isFeatured;
Offers({
this.brandName,
this.brandLogo,
this.id,
this.title,
this.shortDescription,
this.categories,
this.subcategories,
this.offerContactAddress,
this.offerContactWebsite,
this.offerContactTelephone,
this.offerContactEmail,
this.offerContactMobileNumber,
this.aboutThisOffer,
this.details,
this.locationDetails,
this.offerValidity,
this.keywordList,
this.images,
this.mobileofflineimages,
this.categoryIds,
this.discount,
this.isNewOffer,
this.specialOfferContent,
this.createdDate,
this.updatedDate,
this.isPreview,
this.isFeatured,
});
factory Offers.fromJson(Map<String, dynamic> json) => Offers(
brandName: json["brandName"],
brandLogo: json["brandLogo"],
id: json["id"],
title: json["title"],
shortDescription: json["shortDescription"],
categories: json["categories"],
subcategories: json["subcategories"],
offerContactAddress: json["offerContactAddress"],
offerContactWebsite: json["offerContactWebsite"],
offerContactTelephone: json["offerContactTelephone"],
offerContactEmail: json["offerContactEmail"],
offerContactMobileNumber: json["offerContactMobileNumber"],
aboutThisOffer: json["aboutThisOffer"],
details:
List<Detail>.from(json["details"].map((x) => Detail.fromJson(x))),
locationDetails: List<LocationDetail>.from(
json["locationDetails"].map((x) => LocationDetail.fromJson(x))),
offerValidity: Offer.fromJson(json["offerValidity"]),
keywordList: KeywordList.fromJson(json["keywordList"]),
images: List<String>.from(json["images"].map((x) => x)),
mobileofflineimages: json["mobileofflineimages"],
categoryIds: List<int>.from(json["categoryIds"].map((x) => x)),
discount: json["discount"],
isNewOffer: json["isNewOffer"],
specialOfferContent: json["specialOfferContent"],
createdDate: json["CreatedDate"],
updatedDate: json["UpdatedDate"],
isPreview: json["isPreview"],
isFeatured: json["isFeatured"],
);
Map<String, dynamic> toJson() => {
"brandName": brandName,
"brandLogo": brandLogo,
"id": id,
"title": title,
"shortDescription": shortDescription,
"categories": categories,
"subcategories": subcategories,
"offerContactAddress": offerContactAddress,
"offerContactWebsite": offerContactWebsite,
"offerContactTelephone": offerContactTelephone,
"offerContactEmail": offerContactEmail,
"offerContactMobileNumber": offerContactMobileNumber,
"aboutThisOffer": aboutThisOffer,
"details": List<dynamic>.from(details.map((x) => x.toJson())),
"locationDetails":
List<dynamic>.from(locationDetails.map((x) => x.toJson())),
"offerValidity": offerValidity.toJson(),
"keywordList": keywordList.toJson(),
"images": List<dynamic>.from(images.map((x) => x)),
"mobileofflineimages": mobileofflineimages,
"categoryIds": List<dynamic>.from(categoryIds.map((x) => x)),
"discount": discount,
"isNewOffer": isNewOffer,
"specialOfferContent": specialOfferContent,
"CreatedDate": createdDate,
"UpdatedDate": updatedDate,
"isPreview": isPreview,
"isFeatured": isFeatured,
};
}
class Detail {
String type;
String name;
String content;
Detail({
this.type,
this.name,
this.content,
});
factory Detail.fromJson(Map<String, dynamic> json) => Detail(
type: json["type"],
name: json["name"],
content: json["content"],
);
Map<String, dynamic> toJson() => {
"type": type,
"name": name,
"content": content,
};
}
class KeywordList {
List<String> keywords;
KeywordList({
this.keywords,
});
factory KeywordList.fromJson(Map<String, dynamic> json) => KeywordList(
keywords: List<String>.from(json["keywords"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"keywords": List<dynamic>.from(keywords.map((x) => x)),
};
}
class LocationDetail {
String latitude;
String longitude;
String address;
LocationDetail({
this.latitude,
this.longitude,
this.address,
});
factory LocationDetail.fromJson(Map<String, dynamic> json) => LocationDetail(
latitude: json["latitude"],
longitude: json["longitude"],
address: json["address"],
);
Map<String, dynamic> toJson() => {
"latitude": latitude,
"longitude": longitude,
"address": address,
};
}
class Pageheaderdetail {
dynamic title;
dynamic content;
dynamic bannerTitle;
dynamic bannerImage;
dynamic metaTitle;
dynamic metaDescription;
dynamic metaKeywords;
dynamic pageId;
dynamic emailAddress;
dynamic userId;
dynamic preferedName;
Pageheaderdetail({
this.title,
this.content,
this.bannerTitle,
this.bannerImage,
this.metaTitle,
this.metaDescription,
this.metaKeywords,
this.pageId,
this.emailAddress,
this.userId,
this.preferedName,
});
factory Pageheaderdetail.fromJson(Map<String, dynamic> json) =>
Pageheaderdetail(
title: json["title"],
content: json["content"],
bannerTitle: json["bannerTitle"],
bannerImage: json["bannerImage"],
metaTitle: json["metaTitle"],
metaDescription: json["metaDescription"],
metaKeywords: json["metaKeywords"],
pageId: json["PageId"],
emailAddress: json["emailAddress"],
userId: json["userId"],
preferedName: json["preferedName"],
);
Map<String, dynamic> toJson() => {
"title": title,
"content": content,
"bannerTitle": bannerTitle,
"bannerImage": bannerImage,
"metaTitle": metaTitle,
"metaDescription": metaDescription,
"metaKeywords": metaKeywords,
"PageId": pageId,
"emailAddress": emailAddress,
"userId": userId,
"preferedName": preferedName,
};
}
这是您 json 数据的模型类
{
"responseModel": {
"data": [
{
"offers": {
"brandName": "Yoga",
"brandLogo": "364t3.jpg",
"id": 2214,
"title": "Up to 40% discount on yoga classes",
"shortDescription": "<p>Up to 40% discount </p>",
"categories": null,
"subcategories": null,
"offerContactAddress": "<p>Kolkata</p>",
"offerContactWebsite": "http://www.google.com",
"offerContactTelephone": "123 456",
"offerContactEmail": "abcd@gmail.com",
"offerContactMobileNumber": null,
"aboutThisOffer": "<p>Yoga is a science of healthy and happy living. </p>",
"details": [
{
"type": "OfferValue",
"name": "Offer",
"content": "<p>My Content</p>"
}
],
"locationDetails": [
{
"latitude": "25.32",
"longitude": "55.23",
"address": "Kolkata"
},
{
"latitude": "25.1239",
"longitude": "55.643",
"address": "Mumbai"
}
],
"offerValidity": {
"validFrom": "10/17/2013",
"validTo": "12/31/2020"
},
"keywordList": {
"keywords": [
"Yoga",
"Weight Loss"
]
},
"images": [
"20pic2.jpg",
"20pic1.jpg"
],
"mobileofflineimages": null,
"categoryIds": [
4316
],
"discount": "10",
"isNewOffer": false,
"specialOfferContent": null,
"CreatedDate": "27/05/2018 12:47:42",
"UpdatedDate": "11/12/2019 08:35:55",
"isPreview": false,
"isFeatured": false
},
"Id": 22184,
"CreateDate": "2018-05-27T12:47:42",
"OfferDatefromTo": {
"validFrom": "2013-10-17T00:00:00",
"validTo": "2020-12-31T00:00:00"
},
"IsPreview": false,
"BrandId": 6542,
"CategoryIds": [
4316
],
"UpdatedDate": "2019-12-11T08:35:55",
"NotificationTrackID": "00000000-0000-0000-0000-000000000000",
"NotificationPriority": 0,
"NotificationPriorityOrderName": null,
"ContactAddress": "Address",
"IsPushNotification": false
}
],
"pageheaderdetail": {
"title": null,
"content": null,
"bannerTitle": null,
"bannerImage": null,
"metaTitle": null,
"metaDescription": null,
"metaKeywords": null,
"PageId": null,
"emailAddress": null,
"userId": null,
"preferedName": null
},
"status": 1,
"error": null
}
}
这是您提供的 json,请检查代码并告诉我它是否有效。
class OfferModel {
String brandName;
String brandLogo;
int id;
String title;
String shortDescription;
OfferModel({
this.brandName,
this.brandLogo,
this.id,
this.title,
this.shortDescription,
});
factory OfferModel.fromJson(Map json) {
return OfferModel(
brandName: json['brandName'],
brandLogo: json['brandLogo'],
id: json['id'],
title: json['title'],
shortDescription: json['shortDescription'],
);
}
}
class DataModel {
int id;
String createDate;
OfferModel offer;
DataModel({this.id, this.createDate, this.offer});
factory DataModel.fromJson(Map json) {
return DataModel(
id: json['Id'],
createDate: json['CreateDate'],
offer: OfferModel.fromJson(json['offers']));
}
}
class ResponseModel {
List<DataModel> data;
ResponseModel({this.data});
factory ResponseModel.fromJson(Map json) {
List<DataModel> datas = [];
json['responseModel']['data'].forEach((item) => datas.add(DataModel.fromJson(item)));
return ResponseModel(data: datas);
}
}
void main() {
var responseModel = ResponseModel.fromJson(jsonDecode(myJson));
print('Responseeeeee= ${responseModel.data.first.offer.brandName}');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.