如何在Flutter中将嵌套的Json作为HTTP发布请求发送到正文中

时间:2020-04-18 12:15:47

标签: http flutter dart

我正在尝试从我一直在使用的flutter应用程序发出的http发布请求之一中,将嵌套的Json作为正文发送。

{
      "user" : {
        "UserName": "username",
        "password":"password",
        "Name": "name",
        "Email": "email"
      }
}

我尝试了许多在线可用的方法来执行此操作,但是每次遇到500错误时,都会这样做。下面是一个将其转换为Json的类。

class SignupJson {
  String username;
  String email;
  String name;
  String password;

  SignupJson(this.email, this.name, this.password, this.username);

  Map toJson() =>{"user":{
    'UserName': username,
    'Name': name,
    'password': password,
    'Email': email
  }};

}

然后将其传递给发布请求。 (我放了一个任意的网址链接)

Future<int> attemptSignup ({String username, String password, String name, String email}) async {



    SignupJson data = SignupJson(username: username, password: password, name: name, email: email);
    var url = 'url';

    String body = jsonEncode(json);

    var res = await http.post(url,
    body: body);
    return res.statusCode;

  }

3 个答案:

答案 0 :(得分:0)

添加标题如下:

Map<String, String> headers = {HttpHeaders.contentTypeHeader: "application/json"};

然后发布请求:

var res = await http.post(url, headers: headers, body: body);

答案 1 :(得分:0)

将地图定义为<String, dynamic>,例如:

Map<String, dynamic> data = {
"User": {
          "UserName":"username",
          "Password":"password"
    }
};

并将以下内容添加到标题中:

HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('Accept', 'application/json');
request.headers.set('Content-type', 'application/json');
request.add(utf8.encode(json.encode(data)));
HttpClientResponse response = await request.close();
String reply = await utf8.decoder.bind(response).join();
httpClient.close();

答案 2 :(得分:0)

最近2天,我一直在这个问题上受困。以下是我如何解决问题的方法

Future<int> attemptSignup ({String username, String password, String name, String email}) async {


SignupJson data = SignupJson(username: username, password: password, name: name, email: email);
var url = 'url';

String body = jsonEncode(data);     

//here jsonEncode(data) return String bt in http body you are passing Map value

//So you have to convert String to Map
Map bodyMap = jsonDecode(body);         

// your nested json data
var bodyData = {       // where var store <String, dynamic> data as your demand
      "user" : bodyMap  
};


var res = await http.post(url,
body: bodyData,
headers: {"Content-Type": "application/json",},
);

return res.statusCode;

}

确保在http

中添加标题