Reputation: 63
I want to use JSON-RPC to control an application called aria2. I can control it when it doesn't need params. But I tried many ways, I never successful in controlling it with params.
Some of the code I've tried is like this:
if (secret != null && secret != "")
json = JsonConvert.SerializeObject(new JObject { ["jsonrpc"] = "2.0", ["id"] = "m", ["method"] = "aria2.addUri", ["params"] = { "token:" + secret, "[http://csharp.org/file.zip]" } });
else
json = JsonConvert.SerializeObject(new JObject { ["jsonrpc"] = "2.0", ["id"] = "m", ["method"] = "aria2.addUri", ["params"] = @"[http://csharp.org/file.zip]" });
I also tried:
if (secret != null && secret != "")
string json = "{\"jsonrpc\": \"2.0\",\"method\": \"aria2.addUri\",\"params\": {\"token:\"" + secret + "\",\"http://csharp.org/file.zip\"},\"id\": \"m\"}";
else
string json = "{\"jsonrpc\": \"2.0\",\"method\": \"aria2.addUri\",\"params\": {\"http://csharp.org/file.zip\"},\"id\": \"m\"}";
And I have tried many combinations and permutations with [{'"
but nothing works.
Here is the RPC guide about aria2 for Python: https://aria2.github.io/manual/en/html/aria2c.html#rpc-authorization-secret-token
Upvotes: 1
Views: 2140
Reputation: 63
Here is the solution may some beginners want to know.
First, know what you want to output, in this case is:
{"jsonrpc":"2.0","id":"m","method":"aria2.addUri","params":["token:secret",["http://csharp.org/file.zip"]]}
Result is here: http://jsoneditoronline.org/?id=4ee8fb1e0314e124bd3ab7d4b2ed19f1
And then, the little tip, []
is outside from the params's value, so they're arrays, not string. It can't use ["params"] = {}
, it also won't cover string to array, for example, following wrong code:
JsonConvert.SerializeObject(new JObject { ["params"] = "[\"token:secret\", [\"http://csharp.org/file.zip\"]]" });
only get:
{"params":"[\"token:secret\", [\"http://csharp.org/file.zip\"]]"}
The most important is the format of token, it's not a
JProperty()
inJObject()
, it's just a string in params'sJArray()
. And uri is also in params'sJArray()
'sJArray()
. So the right version is:
JArray param = new JArray { "token:secret", new JArray { "http://csharp.org/file.zip" } };
string json = JsonConvert.SerializeObject(new JObject { ["jsonrpc"] = "2.0", ["id"] = "m", ["method"] = "aria2.addUri", ["params"] = param });
JArray()
is []
, JObject()
is {}
; JArray()
≠ JObject()
.If we don't need
JsonConvert()
, the right version is easy:
string json = "{ \"jsonrpc\": \"2.0\", \"id\": \"m\", \"method\": \"aria2.addUri\", \"params\": [\"token:secret\", [\"http://csharp.org/file.zip\"]] }";
"
to '
in this case.Upvotes: 1