String 如何将结构或JSON转换为原始字符串?
我有测试,我需要向我的服务器发送JSON数据。我有以下测试:String 如何将结构或JSON转换为原始字符串?,string,struct,rust,hyper,String,Struct,Rust,Hyper,我有测试,我需要向我的服务器发送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,
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]:特性绑定'hyper::client::Body',但看,这不是问题;问题是:如何将结构或JSON转换为原始字符串,仅此而已。谢谢
我知道错误E0277是关于“Hyper::client::Body:std::convert::From`特性的实现不满足
-->src/main.rs:37:10
|
37.正文(编码的请求)
|^^^^对于`hyper::client::Body,`std::convert::From>`std::string::string::Body,`std::convert::From`特性未实现`
这就是问题所在-实际上有更多的方法可以转换为正文
,文档中没有显示它们1!退房时,您可以看到:
impl<'a> Into<Body<'a>> for &'a str {
#[inline]
fn into(self) -> Body<'a> {
self.as_bytes().into()
}
}
impl<'a> Into<Body<'a>> for &'a String {
#[inline]
fn into(self) -> Body<'a> {
self.as_bytes().into()
}
}
1我将查看这是否是已归档的问题,因为这似乎不正确 我建议您进一步研究错误消息的含义。我只是添加了更完整的示例。如果我可以将JSON或Struct对象转换为原始字符串,那么我就不需要为hyper::client::BodyAnswer实现trait。今晚我要试试这个。直到现在,对我来说,锈迹还没有很高的学习曲线;相反,它以一种简单的方式解决问题,迫使我们思考新的可能性。
impl<'a> RequestBuilder<'a> {
fn body<B: Into<Body<'a>>>(self, body: B) -> RequestBuilder<'a>;
}
impl<'a, R: Read> From<&'a mut R> for Body<'a> {
fn from(r: &'a mut R) -> Body<'a>;
}
impl<'a> Into<Body<'a>> for &'a str {
#[inline]
fn into(self) -> Body<'a> {
self.as_bytes().into()
}
}
impl<'a> Into<Body<'a>> for &'a String {
#[inline]
fn into(self) -> Body<'a> {
self.as_bytes().into()
}
}
let mut response = client.post(url)
.body(&encoded_request)
.send()
.unwrap();