如何将数组数据编码为json?
How to encode array data to json?
- 说我创建了一个 ListView.Builder。
- 我有一个 "Add Job" 按钮可以将工作添加到列表中。
- 让我现在在列表中添加了 2 个工作。我想通过API.
提交这个数组数据
- 我的问题是如何编码地图数组并正确传递它们?
- This image describes what I'm trying to tell.
- 在此先感谢您。
这是请求正文:
{"batch":
[
{"sector_id":1,"company":"Company"},
{"sector_id":2,"company":"Organization"},
......if has more
]
}
我有这个 模型:
class Occupations {
List<Batch> batch;
Occupations({this.batch});
Occupations.fromJson(Map<String, dynamic> json) {
if (json['batch'] != null) {
batch = new List<Batch>();
json['batch'].forEach((v) {
batch.add(new Batch.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.batch != null) {
data['batch'] = this.batch.map((v) => v.toJson()).toList();
}
return data;
}
}
class Batch {
int sectorId;
String company;
Batch({this.sectorId, this.company});
Batch.fromJson(Map<String, dynamic> json) {
sectorId = json['sector_id'];
company = json['company'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sector_id'] = this.sectorId;
data['company'] = this.company;
return data;
}
}
我的POST方法:
createOccupations(int id, String company)async{
var _sectorsUrl = '$_hostUrl/occupations';
String _body ='{"batch":[{"sector_id":id,"company":"$company"}]}';
final _response = await post(
_sectorsUrl,
body: _body,
headers: {
'Content-type':'application/json',
'Accept':'application/json',
}
);
if (_response.statusCode==200) {
return Occupations.fromJson(json.decode(_response.body));
} else {
print(_response.statusCode);
print(_data);
}
}
这是我的 UI:
Column(children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: jobCount,
itemBuilder: (context, index) {
_sectorIdController.add(new TextEditingController());
_companyNameController.add(new TextEditingController());
return Container(
margin: margin10,
padding: padding10,
decoration: BoxDecoration(
border: Border.all(color:black)
),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Sector Id'),
controller: _sectorIdController[index],
),
TextField(
decoration:
InputDecoration(labelText: 'Company Name'),
controller: _companyNameController[index]),
],
),
);
})),
RaisedButton(
child: Text('Add Job'),
onPressed: () {
setState(() {
jobCount++;
});
}),
RaisedButton(child: Text('Submit Occupations'), onPressed: () {}),
])
String jsonEncodedString=json.encode(value);
value 可以是 list、map、int、string、double 等任何对象
示例:
String jsonEncodedString=json.encode({'hello':'i am a map'});
你可以通过API
传递json编码的字符串
解法:
- 我在调用 API 时需要 return 编码的 json 数组。因此,我需要编码 'data'.
createOccupations(int id, var data)async{
var _sectorsUrl = '$_hostUrl/occupations';
final _response = await post(
_sectorsUrl,
body: jsonEncode({"batch":data}), //jsonEncode to encode the data to json
headers: {
'Content-type':'application/json',
'Accept':'application/json',
}
);
if (_response.statusCode==200) {
return Occupations.fromJson(json.decode(_response.body));
} else {
print(_response.statusCode);
print(_data);
}
}
- 创建函数以在用户触发按钮时调用 API。
void _createJobs() {
setState(() {
List<Batch> _listBatch = List<Batch>();
var newList;
for (var i = 0; i < jobCount; i++) {
Batch _batch = Batch(sector_id:_sectorIdController[i].text,company: _companyNameController[i].text);
_listBatch.addAll([_batch]);
}
newList = _listBatch;
_jobAPI.createOccupation(context, newList); // I do not need to encode the data here because when I pass it, I already did encoding as show above.
});
}
- 说我创建了一个 ListView.Builder。
- 我有一个 "Add Job" 按钮可以将工作添加到列表中。
- 让我现在在列表中添加了 2 个工作。我想通过API. 提交这个数组数据
- 我的问题是如何编码地图数组并正确传递它们?
- This image describes what I'm trying to tell.
- 在此先感谢您。
这是请求正文:
{"batch":
[
{"sector_id":1,"company":"Company"},
{"sector_id":2,"company":"Organization"},
......if has more
]
}
我有这个 模型:
class Occupations {
List<Batch> batch;
Occupations({this.batch});
Occupations.fromJson(Map<String, dynamic> json) {
if (json['batch'] != null) {
batch = new List<Batch>();
json['batch'].forEach((v) {
batch.add(new Batch.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.batch != null) {
data['batch'] = this.batch.map((v) => v.toJson()).toList();
}
return data;
}
}
class Batch {
int sectorId;
String company;
Batch({this.sectorId, this.company});
Batch.fromJson(Map<String, dynamic> json) {
sectorId = json['sector_id'];
company = json['company'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sector_id'] = this.sectorId;
data['company'] = this.company;
return data;
}
}
我的POST方法:
createOccupations(int id, String company)async{
var _sectorsUrl = '$_hostUrl/occupations';
String _body ='{"batch":[{"sector_id":id,"company":"$company"}]}';
final _response = await post(
_sectorsUrl,
body: _body,
headers: {
'Content-type':'application/json',
'Accept':'application/json',
}
);
if (_response.statusCode==200) {
return Occupations.fromJson(json.decode(_response.body));
} else {
print(_response.statusCode);
print(_data);
}
}
这是我的 UI:
Column(children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: jobCount,
itemBuilder: (context, index) {
_sectorIdController.add(new TextEditingController());
_companyNameController.add(new TextEditingController());
return Container(
margin: margin10,
padding: padding10,
decoration: BoxDecoration(
border: Border.all(color:black)
),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Sector Id'),
controller: _sectorIdController[index],
),
TextField(
decoration:
InputDecoration(labelText: 'Company Name'),
controller: _companyNameController[index]),
],
),
);
})),
RaisedButton(
child: Text('Add Job'),
onPressed: () {
setState(() {
jobCount++;
});
}),
RaisedButton(child: Text('Submit Occupations'), onPressed: () {}),
])
String jsonEncodedString=json.encode(value);
value 可以是 list、map、int、string、double 等任何对象 示例:
String jsonEncodedString=json.encode({'hello':'i am a map'});
你可以通过API
传递json编码的字符串解法:
- 我在调用 API 时需要 return 编码的 json 数组。因此,我需要编码 'data'.
createOccupations(int id, var data)async{
var _sectorsUrl = '$_hostUrl/occupations';
final _response = await post(
_sectorsUrl,
body: jsonEncode({"batch":data}), //jsonEncode to encode the data to json
headers: {
'Content-type':'application/json',
'Accept':'application/json',
}
);
if (_response.statusCode==200) {
return Occupations.fromJson(json.decode(_response.body));
} else {
print(_response.statusCode);
print(_data);
}
}
- 创建函数以在用户触发按钮时调用 API。
void _createJobs() {
setState(() {
List<Batch> _listBatch = List<Batch>();
var newList;
for (var i = 0; i < jobCount; i++) {
Batch _batch = Batch(sector_id:_sectorIdController[i].text,company: _companyNameController[i].text);
_listBatch.addAll([_batch]);
}
newList = _listBatch;
_jobAPI.createOccupation(context, newList); // I do not need to encode the data here because when I pass it, I already did encoding as show above.
});
}