简体   繁体   中英

how to get data from json to a string in flutter

i am getting the json response from the url,i want to show the data in my screen design(ie append the data to related fields),but i am getting the error as data is null

And here i am adding my controller

     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(() {});
  }

And i am try to append the data to screen as below

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

here storeDetails is my model class name

 {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: }}

this is the response i am getting

json string you post can not use directly. here is what I modified.

{"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":"" 
}

}

you can parse with this

// 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,
    };
}

Based on your question, i can conclude one of two things could cause the error

1)Your api returns null.

2)Your json decoding system is broken somewhere.

To fix the first error you would have to check the code from the api . To fix the second error you could use tools like this json to dart to generate model clasess or go in and manually edit your model, though tedious but most flexible.

Bonus in dart there is Null-aware Operators -> ??. Instead of having the ui display null errors you could place a default placeholder wherever there is null.

Try changing this line of code from

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

to

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

If the above suggestion does not work as expected, you may have to consider what @chunhunghan has pointed out and re-format your JSON data. I had to painstakingly['manually'] reformat the JSON to end up with this:

{
    "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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM