我有测试,我需要发送JSON数据到我的服务器。我有以下测试:如何将结构或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
如果我掉落结构和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()]);
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转换为原始字符串,仅此而已。谢谢。
我建议你对这个错误信息的含义做进一步的研究。 – Shepmaster
我刚刚添加了更多完整的示例。如果我可以将JSON或Struct对象转换为原始字符串,那么我不需要实现hyper :: client :: Body <'_>的特征。问题是关于转换。 –