string - 如何将结构或 JSON 转换为原始字符串?

标签 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,
    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 编码代码并创建一个简单的原始字符串文字并在 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 转换为原始字符串,仅此而已。谢谢。

最佳答案

I Know that the error E0277 is about the implementation of a trait for the "Hyper::client::Body<'_>", but look, this is not the question; the question is: how to convert a struct or JSON into a raw string, nothing more.

转换为原始字符串是 100% 不可能

你看,“原始字符串”一旦源代码被解析就不存在了——它们只是源代码的一个自负。无法将任何内容 转换为原始字符串,因为它不存在可将转换为

所有存在的都是字符串切片(&str)和拥有的字符串(String)。

根据要求,这解决了 OP 的问题,仅此而已。欢迎任何对潜在问题的解决方案感兴趣的人继续阅读。


检查 documentation for RequestBuilder::body ,您可以看到它接受任何可以转换为 Body 的类型:

impl<'a> RequestBuilder<'a> {
    fn body<B: Into<Body<'a>>>(self, body: B) -> RequestBuilder<'a>;
}

如果您随后查看 documentation for Body ,您将看到它存在哪些 From 实现:

impl<'a, R: Read> From<&'a mut R> for Body<'a> {
    fn from(r: &'a mut R) -> Body<'a>;
}

再加上知识From implies Into ,您知道您可以将实现 Read 的任何内容传递给 body。实际上,编译器会在错误消息中告诉您:

error[E0277]: the trait bound `hyper::client::Body<'_>: std::convert::From<std::string::String>` is not satisfied
  --> src/main.rs:37:10
   |
37 |         .body(encoded_request)
   |          ^^^^ the trait `std::convert::From<std::string::String>` is not implemented for `hyper::client::Body<'_>`
   |
   = help: the following implementations were found:
   = help:   <hyper::client::Body<'a> as std::convert::From<&'a mut R>>
   = note: required because of the requirements on the impl of `std::convert::Into<hyper::client::Body<'_>>` for `std::string::String`

这就是问题所在 - 实际上有 更多 方法可以转换为 Body,但文档没有显示它们1! checkout the source ,你可以看到:

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()
    }
}

这意味着您可以传入对字符串的引用,然后将其转换为Body,就像vitalyd guessed一样。 :

let mut response = client.post(url)
    .body(&encoded_request)
    .send()
    .unwrap();

1 我要查看这是否已提交问题,因为这看起来确实不正确。

关于string - 如何将结构或 JSON 转换为原始字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352499/

相关文章:

javascript - XSS - JavaScript 字符串

javascript - 我可以从 document.formID.submit(); 调用 JS 函数吗?

c - 在 C 中使用结构体和指针时遇到问题

postgresql - 如何将 Vec<i32> 转换为 types::array::ArrayBase<Option<i32>> 用于 rust-postgres?

rust - 神秘的借用范围扩展

SQL 为什么使用 isnull(field, '' ) <> '' ?

C 结构中的两个数组

c - 如何复制动态分配的结构数组?

gcc - 使用 Cargo 构建时找不到 `lcrypto` 或 `lssl`

string - 二元运算符 '==' 无法应用于 Swift 2 Xcode 7 中类型 'String!' 和 '[String]' 的操作数