Flutter:Json解析
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter:Json解析相关的知识,希望对你有一定的参考价值。
我正在尝试在Flutter中解析API响应。这是API响应的样子。如何在Flutter中解析相同内容?我想解析所有值。
C0]方法中的[parsedJson
参数具有所有值。我确定我在解析时做错了。
非常感谢您的帮助!预先感谢。
fromJson
这是我试图在OfferModel.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
}
}
答案
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;
}
这是主要的ui页面,数据从您提供的assests json加载
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<YouData> 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 = youDataFromJson(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()),
],
);
}),
)),
);
}
}
这是您的json数据的模型类
// To parse this JSON data, do
//
// final youData = youDataFromJson(jsonString);
import 'dart:convert';
YouData youDataFromJson(String str) => YouData.fromJson(json.decode(str));
String youDataToJson(YouData data) => json.encode(data.toJson());
class YouData {
ResponseModel responseModel;
YouData({
this.responseModel,
});
factory YouData.fromJson(Map<String, dynamic> json) => YouData(
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,
th以上是关于Flutter:Json解析的主要内容,如果未能解决你的问题,请参考以下文章