Reputation: 25
I am very new to Flutter, and programming as a whole, and am looking for some help. I have some code which currently posts in JSON correctly, but I want it to post as an array instead and I am not really sure on how to do that.
I have seen and tried a few different solutions, but am unsure exactly how to implement them into my code to make them work.
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
import 'package:intl/intl.dart';
import 'contact.dart';
class ContactService {
static const _serviceUrl = 'https://******.com/';
static final _headers = {'Content-Type': 'application/json'};
Future<Contact> createContact(Contact contact) async {
try {
String json = _toJson(contact);
final response =
await http.post(_serviceUrl, headers: _headers, body: json);
var c = _fromJson(response.body);
return c;
} catch (e) {
print('Server Exception!!!');
print(e);
return null;
}
}
Contact _fromJson(String json) {
Map<String, dynamic> map = jsonDecode(json);
var contact = new Contact();
contact.firstName = map['First Name'];
contact.lastName = map ['Last Name'];
contact.dob = new DateFormat.yMd().parseStrict(map['dob']);
contact.phone = map['phone'];
contact.email = map['email'];
contact.gender = map['gender'];
return contact;
}
String _toJson(Contact contact) {
var mapData = new Map();
mapData["first_name"] = contact.firstName;
mapData["last_name"] = contact.lastName;
mapData["dob"] = new DateFormat.yMd().format(contact.dob);
mapData["phone"] = contact.phone;
mapData["email"] = contact.email;
mapData["gender"] = contact.gender;
String json = jsonEncode(mapData);
return json;
}
}
Other lib file (contact.dart):
class Contact {
String firstName;
String lastName;
DateTime dob;
String phone = '';
String email = '';
String gender = '';
I would like it to post to my URL as a JSON Array rather than just a line of JSON code.
Upvotes: 0
Views: 1548
Reputation: 25
I figured out how to make it appear in array form.
json = '['+ json +']';
I added this line of code in right before the last line of code. Doing this added the square brackets I needed in order for the back-end to receive it correctly.
Upvotes: 0
Reputation: 824
Just use a List
instead of a Map then use the dart:convert
package as below.
import 'dart:convert';
final List<String> data = ["one", "two", "three", "four"];
final String jsonData = json.encode(data);
print(jsonData);
Upvotes: 1