archmedis
archmedis

Reputation: 380

convert json to dart

I am a beginner in Flutter, I just want to know how to print productA and 220 in console. The below is json file and also create dart file below.

{
  "status": true,
  "message": "Data returned successfull",
  "data": {
    "products": [
      {
        "productName": "productA",
        "productPrice": "220.00",
      }
    ]
  }
}

Product.dart

class Product {
  bool status;
  String message;
  Data data;

  Product({this.status, this.message, this.data});

  Product.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    message = json['message'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }
}

class Data {
  List<Products> products;

  Data({this.products});

  Data.fromJson(Map<String, dynamic> json) {
    if (json['products'] != null) {
      products = new List<Products>();
      json['products'].forEach((v) {
        products.add(new Products.fromJson(v));
      });
    }
  }
}

class Products {
  String prodName;
  String prodRkPrice;

  Products({this.prodName, this.prodRkPrice});

  Products.fromJson(Map<String, dynamic> json) {
    prodName = json['prodName'];
    prodRkPrice = json['prodRkPrice'];
  }
}




But still don't know how to print those values.


fetchData() async {
    try {
      String extractedData =
          await http.get('json url').toString();

      final parsed = jsonDecode(extractedData).cast(Map<String, dynamic>());

      final products = Product.fromJson(parsed);

      print(products);

      //print(json.decode(response.body));
      //print(response[0]);
    } catch (error) {
      throw (error);
    }
  }


I have tried using this method but getting errors, don't know how to parse and print those values? Please help me I am a beginner in Flutter

Upvotes: 0

Views: 470

Answers (5)

Kamal Bunkar
Kamal Bunkar

Reputation: 1452

To access the Product A and 220, first you should convert json response into dart object. I Try free online JSON to Dart convertor and here is dart object class

class product_model {
  bool status;
  String message;
  Data data;

  product_model({this.status, this.message, this.data});

  product_model.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    message = json['message'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    data['message'] = this.message;
    if (this.data != null) {
      data['data'] = this.data.toJson();
    }
    return data;
  }
}

class Data {
  List<Products> products;

  Data({this.products});

  Data.fromJson(Map<String, dynamic> json) {
    if (json['products'] != null) {
      products = new List<Products>();
      json['products'].forEach((v) {
        products.add(new Products.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.products != null) {
      data['products'] = this.products.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Products {
  String productName;
  String productPrice;

  Products({this.productName, this.productPrice});

  Products.fromJson(Map<String, dynamic> json) {
    productName = json['productName'];
    productPrice = json['productPrice'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['productName'] = this.productName;
    data['productPrice'] = this.productPrice;
    return data;
  }
}

To access the Product A and value 220, Please use below code.

 final Map<String, dynamic> parsed = await wrapper.get_CategoryFull(catid);
final model = product_model.fromJson(parsed);
     if (model.data.length > 0) {    
       if (model.products.length > 0) {
              for (int i = 0; i < model.products.length; i++) {
                print(" product name " +model.products[i].productName);
                print(" product price " +model.products[i].productPrice);
               
              }
        
            } 
    }

Upvotes: 0

Renzo Rosas V.
Renzo Rosas V.

Reputation: 11

String urlBase = "https://.....";

Future fetchData async {

var jsonResponse;
var response = await http.get("$urlBase");

if (response != null && response.statusCode == 200) {
  jsonResponse = json.decode(response.body);

 Object obj= jsonDecode(response.body);

  return obj;
} else {
  //do something else
}

}

Upvotes: 0

Serg Metelin
Serg Metelin

Reputation: 1114

This should work:

Map<String, dynamic> message = jsonDecode('{"status": true,"message": "Data returned successfull","data": {"products": [{"productName": "productA","productPrice": "220.00"}]}}');
print(message["data"]["products"][0]["productName"]);

What errors are you getting?

Upvotes: 1

Muhammad Tameem Rafay
Muhammad Tameem Rafay

Reputation: 4575

Please try this function

fetchData() async {
    try {
      var extractedData = await http.get('json url');
      Product finalResponse = Product.fromJson(jsonDecode(extractedData.body)); 
      print(finalResponse.products[0].productName);                   
      print(finalResponse);    
    } catch (error) {
      throw (error);
    }
  }

Upvotes: 0

Try
Try

Reputation: 3469

Change your fetchData to:

Future<void> fetchData() async {
  try {
    Response response = await http.get('json url'); //getting the response without .toString
    Map<String, dynamic> extractedData = jsonDecode(response.body); //converting the response

    Product products = Product.fromJson(extractedData);

    products.data.products.forEach((product) {
      print(product.prodName);
      print(product.prodRkPrice);
    });

  } catch (error) {
    throw (error);
  }
}

Just remember to match the same attribute names of the api in the Products class:

Products.fromJson(Map<String, dynamic> json) {
    prodName = json['productName'];
    prodRkPrice = json['productPrice'];
}

Upvotes: 1

Related Questions