Send correct JSON as parameter to RPC(将正确的JSON作为参数发送到RPC)
本文介绍了将正确的JSON作为参数发送到RPC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要对第三方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""]}
据我所知,我的错误是参数是一个数组([]),而不是一个对象({})。根据我的方法,如何才能获得正确的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));
这篇关于将正确的JSON作为参数发送到RPC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:将正确的JSON作为参数发送到RPC
基础教程推荐
猜你喜欢
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
