【问题标题】:How to post json with nested json data using http in flutter?如何在flutter中使用http发布带有嵌套json数据的json?
【发布时间】:2021-12-06 04:13:09
【问题描述】:

我想使用 flutterhttp 将包含另一个 json 数据的 json 数据发布到 API 中

这是我要发送的数据示例

{sales_representative: 1,
 doctor: 1,
 remark: My Remark,
 date: 2021-12-05,
medicines: [
{medicine: 1,
 quantity_type: Tablet,
 quantity: 55
},
 {medicine: 1,
 quantity_type: Tablet,
 quantity: 5
}
]
}

这是我的 API 方法

static Future postSale(body) {
    return http.post(Uri.parse('http://192.168.56.1:8000/api/sales/'),
        body: body);
  }

但是颤振给了我这个错误:

Unhandled Exception: type 'List<Map<String, dynamic>>' is not a subtype of type 'String' in type cast

【问题讨论】:

    标签: flutter http


    【解决方案1】:

    我发现了我的问题:

    1. 我没有用jsonEncode包裹身体。
    2. 我没有指定标题。

    这是我为了让它工作而做的。

    return http.post(Uri.parse('http://192.168.56.1:8000/api/sales/'),
            headers: {
              'Content-Type': 'application/json',
            },
            body: jsonEncode(body));
      }
    

    【讨论】:

      【解决方案2】:

      请这样做。

      var data ={};
         var medicines = [];
         var medicineData ={};  
        
        data["sales_representative"] = 1;
        data["doctor"] =1;
        data["remark"]="my remarks";
        data["date"] = "2021-12-05";
        
        for(int i=0;i<2; i++)
        {
             medicineData ={}; 
             medicineData["medicine"] =1;
             medicineData["quantity_type"] = "Tablet";
             medicineData["quantity"] =5;
          
            medicines.add(medicineData);
        }
        
        data["medicines"] = medicines;
      

      并像这样传递给这个 api 请求

      http.post(Uri.parse('apiUrl'),
              headers: {
                'Content-Type': 'application/json',
              },
              body: jsonEncode(data));
        }
      

      下面是json.encode(data)的输出

      {
        "sales_representative": 1,
        "doctor": 1,
        "remark": "my remarks",
        "date": "2021-12-05",
        "medicines": [
          {
            "medicine": 1,
            "quantity_type": "Tablet",
            "quantity": 5
          },
          {
            "medicine": 1,
            "quantity_type": "Tablet",
            "quantity": 5
          }
        ]
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-12
        • 2021-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        相关资源
        最近更新 更多