1

I am trying to write a custom Json serializer and deserializer for WebHeaderCollection or NameValueCollection class in C#. Since, they are system classes i can't create a custom serializer that needs an attribute to be added to the classes.

I have this so far:

 public class KeysJsonConverter : JsonConverter
 {


    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null)
            return;

        var collection = (NameValueCollection)value;

        writer.WriteStartObject();

        foreach (string name in collection)
        {
            writer.WritePropertyName(name);
            writer.WriteValue(collection.Get(name));
        }

        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //What should i do here to get a NameValueCollection from serialized json string
    }
}

It works for the following:

class Program
{
    static void Main(string[] args)
    {
        var collection = new NameValueCollection { {"a", "1" }, {"b", "2" } };

        var settings = new JsonSerializerSettings();

        settings.Converters.Add(new KeysJsonConverter());

        var json = JsonConvert.SerializeObject(collection, Formatting.Indented, settings);

        Console.WriteLine(json);
    }
}

It serializes the NameValueCollection into a json string. But i am unable to get back the NameValueCollection object through deserialization.

NB: One way to do it is to convert them to dictionary and then doing the serialization/deserialization. However, that will not serve my purpose.

0 Answers0