JsonConvert SerializeObject未正确序列化字符串数组

时间:2018-06-15 14:57:16

标签: c# json serialization json.net json-serialization

我使用以下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();
    //...
}

我从服务器上收到以下错误*:

  

无法从VALUE_STRING

中反序列化java.lang.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() ?? "");
 }

1 个答案:

答案 0 :(得分:1)

您的问题出在objectToDictionary方法中,字符串数组的ToString实现只返回"System.String[]"

你必须改变你的实现,以便Json.Net直接接收字符串数组,他将弄清楚如何序列化它。

相关问题