gpt4 book ai didi

c# - Newtonsoft JSON - 数组未正确序列化

转载 作者:行者123 更新时间:2023-11-30 16:15:55 26 4
gpt4 key购买 nike

在我的代码中,我有一个函数可以向我的比特币服务器创建 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);
}
}

关于c# - Newtonsoft JSON - 数组未正确序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com