我有測試,我需要發送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 <'_>的特徵。問題是關於轉換。 –