【发布时间】:2018-06-15 14:57:15
【问题描述】:
我正在使用以下 RestConnector 将一些 JSON 发布到 REST 服务器:
using Newtonsoft.Json;
public static T httpPost(String myURL, Dictionary<string, string> data) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURL);
Console.WriteLine("Sending Request to: " + myURL);
request.Method = "POST";
var json = JsonConvert.SerializeObject(data);
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("JSON: "+ json);
Console.WriteLine("");
Console.WriteLine("");
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(json);
request.ContentType = "application/json";
request.ContentLength = byte1.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
//...
}
我从服务器收到以下错误*:
无法将 java.lang.String[] 的实例反序列化出 VALUE_STRING
经过进一步调查,这是发布的原始 JSON:
{
"tag1":"val1",
"tag2":"System.String[]",
...
}
如何序列化这个对象,以便正确发送数组?
例子:
{
"tag1":"val1",
"tag2":[],
...
}
编辑:
这是我创建要序列化的对象的地方:
MyObject mo =new MyObject();
mo.tag1= "val1";
mo.tag2= new String[]{};
Dictionary<string, string> input = objectToDictionary(mo);
mo = RestConnector<MyObject>.httpPost("http://example.com", input);
objectToDictionary
public Dictionary<string, string> objectToDictionary(object obj) {
return obj.GetType().GetProperties()
.ToDictionary(x => x.Name, x => x.GetValue(obj)?.ToString() ?? "");
}
【问题讨论】:
-
这里的问题肯定在你的字典里吗?在你开始使用这个方法之前,你已经有了一个字符串字典,其中 tag2 的值是 "System.String[]"
-
编辑添加数据如何添加到字典中
-
是的,所以你的问题是 String[] 上的 ToString 只返回类型的名称。您是否有理由不能将 MyObject 传递给您的 httpPost 方法并对其进行序列化?
标签: c# json serialization json.net json-serialization