使用 HTML c# 反序列化 JSON

Posted

技术标签:

【中文标题】使用 HTML c# 反序列化 JSON【英文标题】:Deserialising JSON with HTML c# 【发布时间】:2014-06-27 05:59:19 【问题描述】:

我正在将一个对象序列化为 JSON,其中包含一个包含 html 的属性

所以我的班级如下所示。

[Serializable]
public class ProductImportModel

  public string ProductName  get; set; 
  public string ShortDescription  get; set; 

所以记录看起来像

 ProductName = "Test Product";
 ShortDescription = "<p>TEST Product</p>";

我认为使用实体框架将其存储到数据库中

 var syncProduct = new SyncProduct();
 syncProduct.ProductId = Guid.NewGuid();
 syncProduct.SerializedProduct = Newtonsoft.Json.JsonConvert.SerializeObject(importProduct);

如果我查看数据库,它看起来很好

  "ProductName":"Test Product","ShortDescription":"<p>TEST Product</p>"

然后我想使用实体框架检索项目,它删除 HTML 标记

  var jsonProduct = context.SyncProducts.FirstOrDefault();

  jsonProduct.SerializedProduct 

  "ProductName":"Test Product","ShortDescription":"pTEST Productp"

我认为这是实体框架中的某种编码问题。 我应该如何检索它?

【问题讨论】:

您应该在保存到数据库时对其进行 HtmlEncode,然后在检索时对其进行解码。 如果 DB 中的 SerializedProduct-column 是 varchar 应该没有问题。是吗? 【参考方案1】:

更改 Json.net 的版本后,它现在似乎可以工作了。应该是版本的bug吧。

【讨论】:

以上是关于使用 HTML c# 反序列化 JSON的主要内容,如果未能解决你的问题,请参考以下文章

使用C# json 二维数组 反序列化

c# 多个json字符串反序列化

使用 C# 反序列化 JSON

无法反序列化 text/html json 响应

C# 无法反序列化这个 json

在 C# 中从 JSON 反序列化数组