在Json反序列化过程中解码HTML编码的字符 [英] Decode Html-encoded characters during Json deserialization

查看:365
本文介绍了在Json反序列化过程中解码HTML编码的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Json.net反序列化Web API调用接收到的json数据.有些字段通常具有html编码的字符,例如"&,如何在反序列化期间自动解码此字符?

I’m using Json.net to deserialize json data received by Web API call. Some fields often have html-encoded characters like " or & How can I have this characters automatically decoded during deserialization?

我提出了两种可能的解决方案:

I came to 2 possible solutions:

  1. 在属性设置器中调用System.Web.HttpUtility.HtmlDecode(),例如:

public string Title
{
    set
    {
        title = System.Web.HttpUtility.HtmlDecode(value);
    }
}

  • 编写自定义的JsonConverter,该自定义JsonConverter在ReadJson()方法中调用System.Web.HttpUtility.HtmlDecode():

  • Writing custom JsonConverter that calls System.Web.HttpUtility.HtmlDecode() in ReadJson() method:

    public class HtmlEncodingConverter : Newtonsoft.Json.JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(String);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return System.Web.HttpUtility.HtmlDecode((string)reader.Value);
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteRawValue(System.Web.HttpUtility.HtmlEncode((string)value));
        }
    }
    

  • 但是有没有内置的解决方案可以在json反序列化期间执行html解码而无需其他代码?

    But is there any built-in solution that allows to perform html-decoding during json deserialization without additional code?

    推荐答案

    System.Net.WebUtility.HtmlDecode()
    

    HttpUtility.HtmlDecode()
    

    是必经之路,关于JsonSerializer的内容没有内置.

    is the way to go, nothing built in regarding the JsonSerializer.

    这篇关于在Json反序列化过程中解码HTML编码的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆