在我的代码中,我有一个向我的比特币服务器创建JSON请求的函数:
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);
[...]
当我通过parameters
时:
int minconf, int maxconf, List<string> addresses
说
0, 9999, ["ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q", "mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]
结果字符串s
如下所示:
"{"jsonrpc":"1.0","id":"1","method":"listunspent","params":[0,9999,"ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q","mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]}"
虽然服务器期望的字符串应该如下所示:
"{"jsonrpc":"1.0","id":"1","method":"listunspent","params":[0,9999,["ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q","mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]]}"
(注意列表周围的额外括号)
如何确保序列化对象符合我想要的格式?
答案 0 :(得分:2)
改变你的foreach循环,如下所示
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);
}
}
答案 1 :(得分:1)
我认为问题出在您要添加到JArray中的List addresses参数中。
如果你检查JArray(道具)的大小,你会在添加地址之前看到,计数是2,这是正确的,而在插入地址后,它变为4。
[ 0, 9999, “ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q” “mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH” ]
您可以将地址包装成复杂类型并将其作为参数传递吗?