C# 将正确的JSON作为参数发送到RPC
我需要向第三方API发送一个rpc,并发送以下JSONC# 将正确的JSON作为参数发送到RPC,c#,json,rpc,C#,Json,Rpc,我需要向第三方API发送一个rpc,并发送以下JSON { "jsonrpc":"2.0", "id":"number", "method":"login.user", "params":{ "login":"string", "password":"string&
{
"jsonrpc":"2.0",
"id":"number",
"method":"login.user",
"params":{
"login":"string",
"password":"string"
}
}
{"jsonrpc":"2.0","id":1,"method":"login.user","params":["\"login\" : \"v.ermachenkov@mangazeya.ru\"","\"password\": \"AmaYABzP2\""]}
我已经创建了一个方法来生成rcp,但是我无法获得要发送的正确JSON
public JObject Post()
{
object[] a_params = new object[] { "\"login\" : \"test@test.ru\"", "\"password\": \"Password\""};
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0");
webRequest.ContentType = "application/json; charset=UTF-8";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = 1;
joe["method"] = "login.user";
if (a_params != null)
{
if (a_params.Length > 0)
{
JArray props = new JArray();
foreach (var p in a_params)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
string s = JsonConvert.SerializeObject(joe);
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
WebResponse webResponse = null;
try
{
using (webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
}
catch (WebException webex)
{
using (Stream str = webex.Response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
var tempRet = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
return tempRet;
}
}
}
catch (Exception)
{
throw;
}
}
据我所知,我的错误是params是一个数组([]),而不是一个对象({})。根据我的方法,如何获得正确的json?我纠正了我的错误。代码应该是
JObject a_params = new JObject { new JProperty("login", "login"), new JProperty("password", "Password") };
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0");
webRequest.ContentType = "application/json; charset=UTF-8";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = "1";
joe["method"] = "login.user";
joe.Add(new JProperty("params", a_params));