将正确的 JSON 作为参数发送到 RPC
Posted
技术标签:
【中文标题】将正确的 JSON 作为参数发送到 RPC【英文标题】:Send correct JSON as parameter to RPC 【发布时间】:2020-10-09 20:08:54 【问题描述】:我需要向第三方 API 创建一个 rpc 并发送以下 JSON
"jsonrpc":"2.0",
"id":"number",
"method":"login.user",
"params":
"login":"string",
"password":"string"
我已经创建了一种方法来制作 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;
使用我的代码,我得到以下 JSON
"jsonrpc":"2.0","id":1,"method":"login.user","params":["\"login\" : \"v.ermachenkov@mangazeya.ru\"","\"password\": \"AmaYABzP2\""]
据我了解,我的错误是 params 是一个数组([])而不是一个对象()。根据我的方法如何才能得到正确的 json?
【问题讨论】:
【参考方案1】:我纠正了我的错误。代码应该是
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));
【讨论】:
以上是关于将正确的 JSON 作为参数发送到 RPC的主要内容,如果未能解决你的问题,请参考以下文章