我有测试,我需要将 JSON 数据发送到我的服务器。我有以下测试:
extern crate hyper;
extern crate rustc_serialize;
use std::io::Read;
use hyper::*;
#[derive(RustcDecodable, RustcEncodable)]
struct LegacyJsonRequest {
jsonrpc: String,
method: String,
params: String,
id: i32,
auth: String,
}
#[test]
fn apiinfo_jsonrpc_tests() {
let client = Client::new();
let url = "http://localhost:6767/api_jsonrpc.php";
let mut http_reader = header::Headers::new();
http_reader.set_raw("Content-Type", vec![b"application/json".to_vec()]);
//TODO: How to use a struct and 'export' it to a raw string literal???
let request_data = LegacyJsonRequest {
jsonrpc: "2.0".to_string(),
method: "apiinfo.version".to_string(),
params: "[]".to_string(),
auth: "[]".to_string(),
id: 1,
};
let encoded_request = rustc_serialize::json::encode(&request_data).unwrap();
let mut response = client.post(url)
.body(encoded_request)
.send()
.unwrap();
}
使用此代码,将返回以下错误:
error[E0277]: the trait bound `hyper::client::Body<'_>: std::convert::From<std::string::String>` is not satisfied
如果我删除 struct 和 JSON 编码的代码并创建一个简单的原始字符串文字并在 body 方法上引用它,它就可以工作。例子:
extern crate hyper;
extern crate rustc_serialize;
use std::io::Read;
use hyper::*;
#[derive(RustcDecodable, RustcEncodable)]
struct LegacyJsonRequest {
jsonrpc: String,
method: String,
params: String,
id: i32,
auth: String,
}
#[test]
fn apiinfo_jsonrpc_tests() {
let client = Client::new();
let url = "http://localhost:6767/api_jsonrpc.php";
let mut http_reader = header::Headers::new();
http_reader.set_raw("Content-Type", vec![b"application/json".to_vec()]);
let request_data =
r#"{"jsonrpc":"2.0", "method": "apiinfo.version", "params": {}, "auth": {}, "id": "1"}"#;
let mut response = client.post(url)
.body(request_data)
.send()
.unwrap();
}
那么:如何将我的结构或 JSON 转换为原始字符串?
我知道错误 E0277 是关于“Hyper::client::Body<'_>”的特征的实现,但是看,这不是问题;问题是:如何将结构或 JSON 转换为原始字符串,仅此而已。谢谢。