Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Html-encoded characters during Json deserialization

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. Calling System.Web.HttpUtility.HtmlDecode() in property setter like:

    public string Title
    {
        set
        {
            title = System.Web.HttpUtility.HtmlDecode(value);
        }
    }
    
  2. 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));
        }
    }
    

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

like image 621
CodeFuller Avatar asked Mar 13 '16 16:03

CodeFuller


People also ask

How do I deserialize a JSON string?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How is HTML decoded?

What is HTML Decoding? HTML Encoding is a way of ensuring text will be accurately shown by a browser. The process of 'HTML decoding' involves undoing a previous 'HTML encoding', replacing particular 'escape sequence' of characters with their normal representation.

What is JsonSerializer deserialize?

Serialization and deserialization in . NET application, JSON data format conversion to . NET objects and vice versa is very common. Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.


1 Answers

System.Net.WebUtility.HtmlDecode()

or

HttpUtility.HtmlDecode()

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

like image 72
Emmanuel Istace Avatar answered Sep 30 '22 14:09

Emmanuel Istace