如何从json中获取数据到flutter中的字符串

时间:2019-08-23 06:51:43

标签: json http flutter

我从网址中获取json响应,我想在屏幕设计中显示数据(即将数据附加到相关字段中),但是由于数据为空,我得到了错误

在这里我要添加控制器

     feacthstoredetailsdata() async {
    Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

    final SharedPreferences prefs = await _prefs;

    print("PRINT ====> " + prefs.getString("BearerToken"));

    var receivedToken = "Bearer " + prefs.getString("BearerToken");
//    var id=1;

    var receivedstoreid=prefs.getString("store_id");

    print("=========================="+receivedstoreid);

    print("PRINT ::: receivedToken ====> " + receivedToken);
    var res = await http.get("http://your domain.com/api/rest/stores/${receivedstoreid}",
      headers: {
        'Authorization': receivedToken
      },
    );
    var decodedjson = jsonDecode(res.body);

    storeDetails = StoreDetails.fromJson(decodedjson);
    var res1 = storeDetails.toJson();
    print(res1);
//    return storeDetails;

    setState(() {});
  }

我试图按如下所示将数据附加到屏幕上

 child: Container(
                  height: 250.0,
                  width: 250.0,
                  margin: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: NetworkImage(storeDetails.data.thumb))),
                ),
              ),
            ),

这里storeDetails是我的模型类名称

 {success: true, data: {store_id: 1, store_image: catalog/stores/asian_spice_market/asian_spice_market_logo.png, thumb: http://bagbash.com/image/cache/catalog/stores/asian_spice_market/asian_spice_market_logo-500x500.png, store_language: en-gb, store_comment: Shop for ¥6000 and get Free delivery., store_open: 10AM-10PM, store_fax: , store_telephone: 0804053636, store_email: kumar4675@i.softbank.jp, store_geocode: , store_address: Yokohama Shi, Naka ku, Noge cho 3-160-4, store_owner: Asian Spice Market, store_name: Asian Spice Market, store_url: http://asianspicemarket.bagbash.com/, longitude: , latitude: }}

这是我得到的答复

3 个答案:

答案 0 :(得分:0)

您发布的

json字符串不能直接使用。这是我修改过的。

{"success": true, 
"data": {
"store_id": 1, 
"store_image": "catalog/stores/asian_spice_market/asian_spice_market_logo.png", 
"thumb": "http://bagbash.com/image/cache/catalog/stores/asian_spice_market/asian_spice_market_logo-500x500.png", 
"store_language": "en-gb", 
"store_comment": "Shop for ¥6000 and get Free delivery.", 
"store_open": "10AM-10PM", 
"store_fax": "", 
"store_telephone": "0804053636", 
"store_email": "kumar4675@i.softbank.jp", 
"store_geocode": "", 
"store_address": "Yokohama Shi, Naka ku, Noge cho 3-160-4", 
"store_owner": "Asian Spice Market, store_name: Asian Spice Market", 
"store_url": "http://asianspicemarket.bagbash.com/", 
"longitude": "", 
"latitude":"" 
}

}

您可以对此进行解析

// To parse this JSON data, do
//
//     final storeDetails = storeDetailsFromJson(jsonString);

import 'dart:convert';

StoreDetails storeDetailsFromJson(String str) => StoreDetails.fromJson(json.decode(str));

String storeDetailsToJson(StoreDetails data) => json.encode(data.toJson());

class StoreDetails {
    bool success;
    Data data;

    StoreDetails({
        this.success,
        this.data,
    });

    factory StoreDetails.fromJson(Map<String, dynamic> json) => new StoreDetails(
        success: json["success"],
        data: Data.fromJson(json["data"]),
    );

    Map<String, dynamic> toJson() => {
        "success": success,
        "data": data.toJson(),
    };
}

class Data {
    int storeId;
    String storeImage;
    String thumb;
    String storeLanguage;
    String storeComment;
    String storeOpen;
    String storeFax;
    String storeTelephone;
    String storeEmail;
    String storeGeocode;
    String storeAddress;
    String storeOwner;
    String storeUrl;
    String longitude;
    String latitude;

    Data({
        this.storeId,
        this.storeImage,
        this.thumb,
        this.storeLanguage,
        this.storeComment,
        this.storeOpen,
        this.storeFax,
        this.storeTelephone,
        this.storeEmail,
        this.storeGeocode,
        this.storeAddress,
        this.storeOwner,
        this.storeUrl,
        this.longitude,
        this.latitude,
    });

    factory Data.fromJson(Map<String, dynamic> json) => new Data(
        storeId: json["store_id"],
        storeImage: json["store_image"],
        thumb: json["thumb"],
        storeLanguage: json["store_language"],
        storeComment: json["store_comment"],
        storeOpen: json["store_open"],
        storeFax: json["store_fax"],
        storeTelephone: json["store_telephone"],
        storeEmail: json["store_email"],
        storeGeocode: json["store_geocode"],
        storeAddress: json["store_address"],
        storeOwner: json["store_owner"],
        storeUrl: json["store_url"],
        longitude: json["longitude"],
        latitude: json["latitude"],
    );

    Map<String, dynamic> toJson() => {
        "store_id": storeId,
        "store_image": storeImage,
        "thumb": thumb,
        "store_language": storeLanguage,
        "store_comment": storeComment,
        "store_open": storeOpen,
        "store_fax": storeFax,
        "store_telephone": storeTelephone,
        "store_email": storeEmail,
        "store_geocode": storeGeocode,
        "store_address": storeAddress,
        "store_owner": storeOwner,
        "store_url": storeUrl,
        "longitude": longitude,
        "latitude": latitude,
    };
}

答案 1 :(得分:0)

根据您的问题,我可以推断出可能导致错误的两件事之一

1)您的api返回null。

2)您的json解码系统在某处损坏。

要解决第一个错误,您将必须检查api中的代码。 要解决第二个错误,您可以使用诸如json to dart之类的工具来生成模型分类,或者进入并手动编辑模型,尽管这很繁琐但最灵活。

飞镖奖励中有Null-aware运算符-> ??。 除了让ui显示null错误外,您还可以在没有null的地方放置默认占位符。

答案 2 :(得分:0)

尝试从以下位置更改此行代码

image: NetworkImage(storeDetails.data.thumb))),

image: NetworkImage(decodedjson['data']['thumb']))),

如果以上建议未如预期那样起作用,则可能必须考虑@chunhunghan指出的内容,然后重新格式化JSON数据。我不得不[手动]重新格式化JSON以结束此操作:

{
    "success": "true",
    "data": {
        "store_id": "1",
        "store_image": "catalog/stores/asian_spice_market/asian_spice_market_logo.png",
        "thumb": "http://bagbash.com/image/cache/catalog/stores/asian_spice_market/asian_spice_market_logo-500x500.png",
        "store_language": "en-gb",
        "store_comment": "Shop for ¥6000 and get Free delivery.",
        "store_open": "10AM-10PM",
        "store_fax": "",
        "store_telephone": "0804053636",
        "store_email": "kumar4675@i.softbank.jp",
        "store_geocode": "",
        "store_address": "Yokohama Shi, Naka ku, Noge cho 3-160-4",
        "store_owner": "Asian Spice Market",
        "store_name": "Asian Spice Market",
        "store_url": "http://asianspicemarket.bagbash.com/",
        "longitude": "",
        "latitude": ""
    }
}

JSON view using Awesome JSON