Newtonsoft.json: Unexpected result when serializing/deserializing MediaTypeHeaderValue

Created on 26 Jun 2017  路  1Comment  路  Source: JamesNK/Newtonsoft.Json

Source/destination types

Source: System.Net.Http.Headers.MediaTypeHeaderValue

Expected behavior

After serialization/deserialization result should match original value

Actual behavior

Additional invalid Parameter inside MediaTypeHeaderValue with NULL Name and "utf-8" Value appear

Steps to reproduce

MediaTypeHeaderValue originalValue = new MediaTypeHeaderValue("application/json")
{
    CharSet = "utf-8"
};

string originalStr = originalValue.ToString(); // application/json; charset=utf-8

string serializedStr = JsonConvert.SerializeObject(originalValue); // {"CharSet":"utf-8","Parameters":[{"Name":"charset","Value":"utf-8"}],"MediaType":"application/json"}

MediaTypeHeaderValue deserializedValue = JsonConvert.DeserializeObject<MediaTypeHeaderValue>(serializedStr); // Additional invalid parameter with NULL Name and "utf-8" Value appear

string deserializedStr = deserializedValue.ToString(); // application/json; charset=utf-8; =utf-8

>All comments

You get that result because the Name property of NameValueHeaderValue isn't settable. A customer JsonConverter is required, or deserialize to a different type.

Was this page helpful?
0 / 5 - 0 ratings