代码之家  ›  专栏  ›  技术社区  ›  Fueled By Coffee

jsonConvert序列化对象未正确序列化字符串数组

  •  1
  • Fueled By Coffee  · 技术社区  · 7 年前

    我将使用以下restconnector向REST服务器发布一些JSON:

    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.St[]的实例反序列化

    进一步调查后,这是发布的原始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);
    

    反对文学的

     public Dictionary<string, string> objectToDictionary(object obj) {
         return obj.GetType().GetProperties()
             .ToDictionary(x => x.Name, x => x.GetValue(obj)?.ToString() ?? "");
     }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Gimly    7 年前

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

    您必须更改实现,以便json.net直接接收字符串数组,他将了解如何序列化它。