简体   繁体   English

C#:使用 RestSharp 将 Json 对象转换为字符串:

[英]C#: Converting Json Object to String using RestSharp:

Below is a working example of an http request I wrote using Python requests.下面是我使用 Python 请求编写的 http 请求的工作示例。 In said example there is a json object I convert to string using the Json Dumps function:在上述示例中,我使用 Json Dumps 函数将一个 json 对象转换为字符串:

data = [
    {"parameterName":"date",
     "values":["-30d"]
    },
    {"parameterName":"category",
     "values":["25","4","2"]
    },
    {"parameterName":"format",
     "values":["pdf"]
    },
    {"parameterName":"readunread","values":["read"]}]
    
request = session.post(
    someUrl,
    headers={ 
        'Host': someUrl,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'en-US,en;q=0.5',
        'Accept-Encoding': 'gzip, deflate, br',
        },
        cookies=response.cookies,
        data = json.dumps(data)
        )

I wanted to find a unnecessarily complicated way to do this another way since Python is too straight forward and the first thing that came to mind was C# (using RestSharp):我想找到一种不必要的复杂方法来做这件事,因为 Python 太简单了,首先想到的是 C#(使用 RestSharp):

var client = new RestSharp.RestClient();
client.BaseUrl = new Uri(someUrl);
var documents = new RestSharp.RestRequest(RestSharp.Method.POST);

documents.AddCookie("cookie",theCookies);
documents.AddHeader("Host",someHostUrl);
documents.AddHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0");
documents.AddHeader("Accept","application/json, text/plain, */*");
documents.AddHeader("Accept-Language", "en-US,en;q=0.5");
documents.AddHeader("Accept-Encoding", "gzip, deflate, br");

string documentsBody = "[{\"parameterName\":\"category\",\"values\":[\"25\",\"4\",\"2\"]},{\"parameterName\":\"format\",\"values\":[\"pdf\"]},{\"parameterName\":\"date\",\"values\":[\"-30d\"]},{\"parameterName\":\"readunread\",\"values\":[\"read\"]}]";

documents.AddBody(documentsBody);
IRestResponse response = client.Execute(documents);

The Python example returns the desired response. Python 示例返回所需的响应。 The C# example does not. C# 示例没有。 I know it is due to the formatting of the payload.我知道这是由于有效载荷的格式。 What is the least obnoxious way to format the payload (as done in the Python example) but in C#?除了在 C# 中,格式化有效负载(如 Python 示例中所做的那样)的最不令人讨厌的方法是什么?

We can try to use JsonConvert.SerializeObject which support from Json.NET that help us easy to serializeObject or deserialize.我们可以尝试使用Json.NET支持的JsonConvert.SerializeObject来帮助我们轻松序列化或反序列化。

We can create a class that represent to carry your parameter data as a strong type.我们可以创建一个类,将您的参数数据表示为强类型。

public class ParameterModel
{
    public string parameterName { get; set; }
    public List<string> values { get; set; }
}

then passing it as parameter in JsonConvert.SerializeObject然后将其作为参数传递给JsonConvert.SerializeObject

string documentsBody = Newtonsoft.Json.JsonConvert.SerializeObject(new List<ParameterModel>{
    new ParameterModel(){ parameterName = "category", values = new List<string>(){"25","4","2"} },
    //....
});

documents.AddBody(documentsBody);
IRestResponse response = client.Execute(documents);

EDIT编辑

if you don't want to create a class for parameter of model, we can try to use the anonymous object .如果您不想为模型的参数创建一个类,我们可以尝试使用匿名对象

var result = Newtonsoft.Json.JsonConvert.SerializeObject(new []{
    new { parameterName = "category", values = new []{"25","4","2"} },
    //....
});

c# online c# 在线

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM