我目前正在开发一个 API,我想将数据列表发布到该 API。 这是一个电子商务示例,因此我需要根据行号传递购物车中的多个商品,行号将自动递增。并且订单应使用相同的订单 ID 但不同的订单号发布。
这就是 Json 的样子 -
{
"VarFID": 1,
"VarCID": 1,
"VarAreaCode": 1,
"VarAge": 250,
"VarB": 20,
"VarF": 1,
"VarC": 256,
"VarF": 1,
"OrderLines": [
{
"OrderID": "SQ/19/10",
"Line No_": 1,
"Date": "2019-04-02 00:00:00",
"Time": "2019-04-02 11:38:48",
"No_": "FAG-033",
"Name": "LC GOLD",
"Quantity":000,
"Unit Price": 10000,
"Amount": 10000,
"Status": "Under Processing",
"Remarks": "VIKRAM",
"VariantCode":3
},
{
"OrderID": "SQ/19/10",
"Line No_": 2,
"Date": "2019-04-02 00:00:00",
"Time": "2019-04-02 11:38:48",
"No_": "F061",
"Name": "LC S - I",
"Quantity": 00,
"Unit Price": 100,
"Amount": 300,
"Status": "Under Processing",
"Remarks": "VIKRAM ",
"VariantCode":2
}
]
}
这是我用来生成数组的代码,数据正在通过,但它只发布一项/行,而不是两项。
void sendData2() async {
mainModel = MainModel(
VarFID: "1",
VarCID: "1",
VarAreaCode: "1",
VarAge: "1",
VarB: "1",
VarF: "1",
VarC: "1",
VarF: "1",
OrderLines: listOrderLines.OrderLines);
var response = await http.post(
Uri.https('softwareonus.com:8082', '/admindealerlist/'),
headers: {"Content-Type": "application/json"},
body: json.encode(mainModel.toJson()),
);
print(" Send Data 2 Response : ${response.body}");
print(" Send Data 2 Response : ${response.statusCode}");
}
我使用 JsonSerialazble 创建了模型类
你正在做
body: json.encode(mainModel.toJson()),
,这是毫无意义的,因为你的模型中的函数 .toJson()
已经为你做了 json.encode(..)
。您应该只需 .post
您的 mainModel.toJson()
到您的 API。
根据您分享的数据。创建 2 个模型类 -
代码片段:
import 'package:json_annotation/json_annotation.dart';
part 'ObjectModel.g.dart'; // you have to use naming convention of like this (yourfilename.g.dart)
@JsonSerializable()
class ObjectModel
{
String orderId;
String lineNo;
//All other variable define here
// Initilize all in the constructor
ObjectModel({this.orderId,this.lineNo,[.... your othersVariable...]});
@override
factory ObjectModel.fromJson(Map<String, dynamic> json) =>
_$ObjectModelFromJson(json);
Map<String, dynamic> toJson() => _$ObjectModelToJson(this);
}
import 'package:json_annotation/json_annotation.dart';
part 'SuperModel.g.dart'; ///you have to use naming convention of like this (yourfilename.g.dart)
@JsonSerializable()
class SuperModel {
String varFid;
String varCID;
// alll othervarialble...
List<ObjectModel> orderLines;
//initilize all in constructor
SuperModel({ this.varFid,this.varCID ,[.....otherVariable],this.orderLines });
factory SuperModel.fromJson(Map<String, dynamic> json) =>
_$SuperModelFromJson(json);
Map<String, dynamic> toJson() => _$SuperModelToJson(this);
}
注意:为了创建模型类,我使用这两个包,并将其放入 dev_dependency 中:
dev_dependencies:
flutter_test:
sdk: flutter
build_runner:
json_serializable: ^3.3.0
现在您必须运行以下命令来生成 g.dart 文件
flutter pub run build_runner build
现在终于可以像这样进行 HTTP Post 请求和模型类了 -
void send() async {
\\SuperModel supermodel = SuperModel ([initialize data to this model class])
var response = await http.post(
Uri.https('softwareonus.com:8082', '/admindealerlist/'),
headers: {"Content-type": "application/json"},
body: json.encode(supermodel .toJson()));
print(response.body);
}
}
您也可以在 Youtube 上观看我的模特课程系列,链接如下:https://youtube.com/playlist?list=PLtIU0BH0pkKpXE-1vC7NswofFPby1OYh-
谢谢:)
更新:
假设您的应用程序中有一个按钮,当您单击该按钮时,您就将数据添加到列表中
class _ListDataState extends State<ListData> {
SuperModel superModel = SuperModel ();
@override
Widget build(BuildContext context) {
// your UI code
}
void add() {
setState(() {
superModel.orderLines.add(ObjectModel(Your all variable initialize here);
});
}
每当您想在列表中添加新订单时,请调用此添加方法。添加所有数据后使用 send 方法发送它
void send() async {
var response = await http.post(
Uri.https('softwareonus.com:8082', '/admindealerlist/'),
headers: {"Content-type": "application/json"},
body: json.encode(supermodel .toJson()));
print(response.body);
}
替换为您的对象类,该对象类必须具有返回 Map 的 toJson() 方法。
将 'dart:convert' 导入到您的 API 函数类中
别忘了添加,
headers: {'Content-type': 'application/json','Accept': application/json'},
Future<bool> addToSaleDetail(List<YourCustomObject> _listOfObject) async {
String unparsedUrl = "$baseUrl/AddMobileListSaleBrief";
var url = Uri.parse(unparsedUrl);
List jsonList = [];
_listOfObject.map((item) => jsonList.add(item.toJson())).toList();
final response = await http.post(
url,
body: json.encode({"finalResponse": jsonList}["finalResponse"]),
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
尝试将您的
mainModel
更改为Map<String, dynamic>
,然后将您的Map<String, dynamic>
编码为json并将其发送到正文。将此 'Content-type': 'application/json'
添加到您的标头中,以使您的请求以 json 形式发送。例如:
List<Map<String, String>> listItem = <Map<String, String>>[];
for (var element in myList) {
Map<String, String> val = {
'product': element.product.id_product.toString(),
'quantity': element.quantity.toString(),
'total': element.total.toString(),
};
listItem.add(val);
}
Map data = {
'pay': pay,
'customer': id_customer.toString(),
'items': listItem, // this is a List
};
final http.Response response = await client.post(
Uri.parse(...), // your url
headers: {
'content-type': 'application/json' // don't forget this one
},
body: jsonEncode(data), // encode my Map to json
);
就是这样! (顺便说一句,这是我的代码示例)