Home > Net >  toJson method is throwing me an error on call
toJson method is throwing me an error on call

Time:03-21

I may need help with this. Basically im getting this exception when calling order.toJson() method. I have been checking the code but seems good for me. If you see an error please let me know.

E/flutter ( 5623): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: 

Converting object to an encodable object failed: Instance of 'OrderItem'
E/flutter ( 5623): #0      _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter ( 5623): #1      _JsonStringifier.writeList (dart:convert/json.dart:736:7)
E/flutter ( 5623): #2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:718:7)
E/flutter ( 5623): #3      _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter ( 5623): #4      _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter ( 5623): #5      _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter ( 5623): #6      JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter ( 5623): #7      JsonCodec.encode (dart:convert/json.dart:172:45)

When calling toJson() method. Here are my classes.

class Order{
  String id;
  String userId;
  String deliverId;     
  String restaurantId;
  List<OrderItem> orderItems;
  double total;
  String orderStatus;
  
  Order({
    required this.id,
    required this.userId,
    required this.deliverId,
    required this.restaurantId,
    required this.orderItems,
    required this.total,
    required this.orderStatus
  });

  Map<String, dynamic> toJson(){
    return {
      'id' : id,
      'userId' : userId,
      'deliverId' : deliverId,
      'restaurantId' : restaurantId,
      'orderItems' : jsonEncode(orderItems),
      'total' : total,
      'orderStatus' : orderStatus
    };
  }
}

OrderItem class

class OrderItem{
  RestaurantModel restaurant;
  List<OrderProduct> products;
  String id;
  OrderItem({
    required this.restaurant, 
    required this.products, 
    required this.id
  });

  Map<String, dynamic> toJson(){
    return {
      'restaurant' : restaurant.toJson(),
      'products' : jsonEncode(products),
      'id' : id,
    };
  }
}

RestaurantModel class

 class RestaurantModel {
  String uid;
  String restaurantName;
  String restaurantAddress;
  String restaurantUrl;
  String restaurantSlogan;
  int stars;
  String cost;
  String category;
  String status;
  DateTime startDate;
  List<Product>? products;


  RestaurantModel({
    required this.uid,
    required this.restaurantName, 
    required this.restaurantAddress, 
    required this.restaurantSlogan, 
    required this.restaurantUrl,
    required this.stars,
    required this.cost,
    required this.category,
    required this.status,
    required this.startDate,
    this.products, 
  });

  
  Map<String, Object?> toJson(){
    return{
      'restaurantName' : restaurantName, 
      'restaurantAddress' : restaurantAddress,
      'restaurantSlogan' : restaurantSlogan,
      'restaurantUrl': restaurantUrl,
      'stars' : stars,
      'cost' : cost,
      'category' : category,
      'status' : status,
      'startDate' : startDate,
    };
  }
}

OrderProduct class

class OrderProduct{
  Product product;
  int quantity;

  OrderProduct({
    required this.product,
    required this.quantity,
  });

  Map<String, dynamic> toJson(){
    return {
      'product' : product.toJson(),
      'quantity' : quantity,
    };
  }
}

Product class

class Product{
  String productId;
  String productName;
  String productDescription;
  double productPrice;
  String productUrl;
  int productLikes;
  String productUnit;

  Product({
    required this.productId,
    required this.productName,
    required this.productDescription,
    required this.productPrice,
    required this.productUrl,
    required this.productLikes,
    required this.productUnit,
    }
  );

  Map<String, dynamic> toJson(){
    return {
      'productId' : productId,
      'productName' : productName,
      'productDescription' : productDescription,
      'productPrice' : productPrice,
      'productUrl' : productUrl,
      'productLikes' : productLikes,
      'productUnit' : productUnit,
    };
  }
}

So basically I'm getting an error when trying to call toJson() method from order.

void addOrderAsync(String userId, Order order) async{
//  here is where im getting the error
    final jsonData = order.toJson();
    final response = await http.post(Uri.parse("$apiUrl/users/$userId/cart/add"),
    headers: <String, String> {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(jsonData),
    );

    if(response.statusCode == 200 || response.statusCode == 201){
      // do something
    }
    else{
      throw Exception("Failed to create user");
    }

  }

CodePudding user response:

try change toJson() to:

Map<String, dynamic> toJson(){
  final Map<String, dynamic> data = new Map<String, dynamic>();
   data['productId'] = this.productId;
   data['productName'] = this.productName;
   data['productDescription'] = this.productDescription;
   data['productPrice'] = this.productPrice;
   data['productUrl'] = this.productUrl;
   data['productLikes'] = this.productLikes;
   data['productUnit'] = this.productUnit;
  return data;

}

CodePudding user response:

Try this:

Map<String, dynamic> toJson(){
    return {
      'id' : id,
      'userId' : userId,
      'deliverId' : deliverId,
      'restaurantId' : restaurantId,
      'orderItems' : orderItems.toJson(),
      'total' : total,
      'orderStatus' : orderStatus
    };
  }

Replace jsonEncode by toJson()

  • Related