Reputation: 9185
In my code I have a function that creates JSON requests to my Bitcoin server:
public static JObject InvokeMethod(string sMethod, params object[] parameters)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Credentials = Credentials;
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "1.0";
joe["id"] = "1";
joe["method"] = sMethod;
if (parameters != null)
{
if (parameters.Length > 0)
{
JArray props = new JArray();
foreach (var p in parameters)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
string s = JsonConvert.SerializeObject(joe);
[...]
When I pass it parameters
of:
int minconf, int maxconf, List<string> addresses
say
0, 9999, ["ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q", "mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]
the resulting string s
looks like:
"{"jsonrpc":"1.0","id":"1","method":"listunspent","params":[0,9999,"ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q","mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]}"
while the string the server is expecting should look like:
"{"jsonrpc":"1.0","id":"1","method":"listunspent","params":[0,9999,["ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q","mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]]}"
(note the extra brackets around the list)
How can I make sure the serialized objects are in my desired format?
Upvotes: 3
Views: 2973
Reputation: 63065
change you foreach loop as below
foreach (var p in parameters)
{
if (p.GetType().IsGenericType && p is IEnumerable)
{
JArray l = new JArray();
foreach (var i in (IEnumerable)p)
{
l.Add(i);
}
props.Add(l);
}
else
{
props.Add(p);
}
}
Upvotes: 2
Reputation: 3746
I think the issue is in the List addresses parameter you want to add into the JArray.
If you check the size of the JArray (props), you will see before adding the addresses in, the count is 2, which is correct, while after the addresses is inserted, it becomes 4.
[ 0, 9999, "ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q", "mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH" ]
Can you wrap the addresses into a complex type and pass that as an argument?
Upvotes: 1