Reputation: 477
I need to make an rpc to a thirh party API and send the following JSON
{
"jsonrpc":"2.0",
"id":"number",
"method":"login.user",
"params":{
"login":"string",
"password":"string"
}
}
I have created a method to make the rcp but i cannot get the correct JSON to be send
public JObject Post()
{
object[] a_params = new object[] { "\"login\" : \"[email protected]\"", "\"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;
}
}
With my code i'm getting the following JSON
{"jsonrpc":"2.0","id":1,"method":"login.user","params":["\"login\" : \"[email protected]\"","\"password\": \"AmaYABzP2\""]}
As i understand my error is that params is an array([]) instead of an object({}). Based on my method how can get the correct json?
Upvotes: 1
Views: 1368
Reputation: 477
I correct my mistake. The code shoukd be
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));
Upvotes: 1