Json.Net unexpected characters (“\”) when serializing my entities

前端 未结 5 1764
野性不改
野性不改 2020-12-15 17:36

I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :

using (MyVoucherEntitie         


        
5条回答
  •  庸人自扰
    2020-12-15 17:38

    Does this one help? I used it in my WebService to return Json content:

    private HttpContent ConvertToJsonContent(object content)
    {
      string jsonObject = JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented);
      return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }
    

    If strings have a "\" the two "\\" will come back. You can avoid this by using Unescape

    private HttpContent ConvertToJsonContent(object content)
    {
      string jsonObject = Regex.Unescape(JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented));
      return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }
    

提交回复
热议问题