简体   繁体   中英

C#: Converting Json Object to String using RestSharp:

Below is a working example of an http request I wrote using Python requests. In said example there is a json object I convert to string using the Json Dumps function:

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):

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. The C# example does not. 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#?

We can try to use JsonConvert.SerializeObject which support from Json.NET that help us easy to serializeObject or deserialize.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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