数组未正确序列化
作者:互联网
在我的代码中,我有一个函数可以向我的比特币服务器创建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);
[...]
当我通过它的参数:
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"]]}"
(请注意列表中的多余括号)
如何确保序列化的对象符合我想要的格式?
解决方法:
如下更改您的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);
}
}
标签:list,serialization,json-net,json,c 来源: https://codeday.me/bug/20191122/2061923.html