I have a situation where an API I'm using is returning inconsistent JSON, which I want to deserialize using JSON.NET. In one case, it returns an object that contains objects (note that the outer "1" can be any number):
{
"1":{
"0":{
"db_id":"12835424",
"title":"XXX"
},
"1":{
"db_id":"12768978",
"title":"YYY"
},
"2":{
"db_id":"12768980",
"title":"ZZZ"
},
"3":{
"db_id":"12768981",
"title":"PPP"
}
}
}
And in another case, it returns an array of objects:
{
"3":[
{
"db_id":"12769199",
"title":"XXX"
},
{
"db_id":"12769200",
"title":"YYY"
},
{
"db_id":"12769202",
"title":"ZZZ"
},
{
"db_id":"12769243",
"title":"PPP"
}
]
}
I have no idea why this inconsistency exists, but this is the format I'm working with. What would be the correct way to deserialize both formats with the JsonConvert.DeserializeObject method?
With the current version of Json.NET (Json.NET 4.5 Release 11), here is a CustomCreationConverter that will handle Json that deserializes sometimes as an object and sometimes as an array.
public class ObjectToArrayConverter<T> : CustomCreationConverter<List<T>> where T : new()
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
List<T> target = new List<T>();
try
{
// Load JObject from stream
JArray jArray = JArray.Load(reader);
// Populate the object properties
serializer.Populate(jArray.CreateReader(), target);
}
catch (JsonReaderException)
{
// Handle case when object is not an array...
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T t = new T();
// Populate the object properties
serializer.Populate(jObject.CreateReader(), t);
target.Add(t);
}
return target;
}
public override List<T> Create(Type objectType)
{
return new List<T>();
}
}
Example Usage:
[JsonObject]
public class Project
{
[JsonProperty]
public string id { get; set; }
// The Json for this property sometimes comes in as an array of task objects,
// and sometimes it is just a single task object.
[JsonProperty]
[JsonConverter(typeof(ObjectToArrayConverter<Task>))]
public List<Task> tasks{ get; set; }
}
[JsonObject]
public class Task
{
[JsonProperty]
public string name { get; set; }
[JsonProperty]
public DateTime due { get; set; }
}
I think this is something that should be possible by creating a JsonCreationConverter. This article can probably help out: http://dotnetbyexample.blogspot.nl/2012/02/json-deserialization-with-jsonnet-class.html
Related
I am trying to use a durable entity in my Azure Function to cache some data. However, when I try to retrieve the entity (state) for the first time, I get an exception indicating an issue during the entity deserialization.
Here is my entity class and related code
[JsonObject(MemberSerialization.OptIn)]
public class ActionTargetIdCache : IActionTargetIdCache
{
[JsonProperty("cache")]
public Dictionary<string, ActionTargetIdsCacheItemInfo> Cache { get; set; } = new Dictionary<string, ActionTargetIdsCacheItemInfo>();
public void CacheCleanup(DateTime currentUtcTime)
{
foreach (string officeHolderId in Cache.Keys)
{
TimeSpan cacheItemAge = currentUtcTime - Cache[officeHolderId].lastUpdatedTimeStamp;
if (cacheItemAge > TimeSpan.FromMinutes(2))
{
Cache.Remove(officeHolderId);
}
}
}
public void DeleteActionTargetIds(string officeHolderId)
{
if (this.Cache.ContainsKey(officeHolderId))
{
this.Cache.Remove(officeHolderId);
}
}
public void DeleteState()
{
Entity.Current.DeleteState();
}
public void SetActionTargetIds(ActionTargetIdsCacheEntry entry)
{
this.Cache[entry.Key] = entry.Value;
}
public Task<ActionTargetIdsCacheItemInfo> GetActionTargetIdsAsync(string officeHolderId)
{
if (this.Cache.ContainsKey(officeHolderId))
{
return Task.FromResult(Cache[officeHolderId]);
}
else
{
return Task.FromResult(new ActionTargetIdsCacheItemInfo());
}
}
// public void Reset() => this.CurrentValue = 0;
// public int Get() => this.CurrentValue;
[FunctionName(nameof(ActionTargetIdCache))]
public static Task Run([EntityTrigger] IDurableEntityContext ctx)
=> ctx.DispatchAsync<ActionTargetIdCache>();
}
public class ActionTargetIdsCacheEntry
{
// officeHolderId
public string Key { get; set; } = string.Empty;
public ActionTargetIdsCacheItemInfo Value { get; set; } = new ActionTargetIdsCacheItemInfo();
}
[JsonObject(MemberSerialization.OptIn)]
public class ActionTargetIdsCacheItemInfo : ISerializable
{
public ActionTargetIdsCacheItemInfo()
{
lastUpdatedTimeStamp = DateTime.UtcNow;
actionTargetIds = new List<string>();
}
public ActionTargetIdsCacheItemInfo(SerializationInfo info, StreamingContext context)
{
lastUpdatedTimeStamp = info.GetDateTime("lastUpdated");
actionTargetIds = (List<string>)info.GetValue("actionTargetIds", typeof(List<string>));
}
[JsonProperty]
public DateTimeOffset lastUpdatedTimeStamp { get; set; } = DateTimeOffset.UtcNow;
[JsonProperty]
public List<string> actionTargetIds { get; set; } = new List<string>();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("lastUpdated", lastUpdatedTimeStamp);
info.AddValue("actionTargetIds", actionTargetIds);
}
}
public interface IActionTargetIdCache
{
void CacheCleanup(DateTime currentUtcTime);
void DeleteActionTargetIds(string officeHolderId);
void DeleteState();
void SetActionTargetIds(ActionTargetIdsCacheEntry item);
// Task Reset();
Task<ActionTargetIdsCacheItemInfo> GetActionTargetIdsAsync(string officeHolderId);
// void Delete();
}
Here is the exception I get during the first attempt to access the state from an orchestration using the GetActionTargetIdsAsync method:
Exception has occurred: CLR/Microsoft.Azure.WebJobs.Extensions.DurableTask.EntitySchedulerException
Exception thrown: 'Microsoft.Azure.WebJobs.Extensions.DurableTask.EntitySchedulerException' in System.Private.CoreLib.dll: 'Failed to populate entity state from JSON: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'PolTrack.CdbGetFunctionApp.ActionTargetIdsCacheItemInfo' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'cache.officeHolderId1', line 1, position 29.'
Inner exceptions found, see $exception in variables window for more details.
Innermost exception Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'PolTrack.CdbGetFunctionApp.ActionTargetIdsCacheItemInfo' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'cache.officeHolderId1', line 1, position 29.
Could someone with the sufficient SO privileges please add the tag azure-durable-entities.
I did manage to get around this by following #silent suggestion. I re-designed the entity class to only use CLR types. In my case, that meant replacing Dictionary<string, ActionTargetIdsCacheItemInfo> with two dictionaries Dictionary<string, List<string>> and Dictionary<string, DateTimeOffset>.
I am trying to create a custom JsonConverter to follow a third party API with a rather complicated object structure, and am a bit hamstrung on a few things. Note I am using .NET 4.7.2, not Core.
I have source objects that look like this, which I have created as objects rather than dictionaries in order to easily integrate them with FluentValidation. The objects will represent json objects in the foreign API. The "Value" is an interfaced item which is eventually converted to one of about 20 concrete types.
public class PDItem : IDictionaryObject<List<IItem>>
{
[JsonProperty]
public string Key { get; set; }
[JsonProperty]
public List<IItem> Value { get; set; }
}
The source json for such an object is a dictionary, whereby the Key is the property, and the value is one of the 20 object types, as so:
{
"checked": [
{
"elementType": "input",
"inputType": "checkbox",
"name": "another_checkbox",
"label": "Another checkbox",
"checked": true
}
]
}
In this case, the object in C# would look something like this:
PDItem item = new PDItem() {
Key = "checked",
Value = new List<IItem>() {
new ConcreteTypeA () {
elementType = "input",
inputType = "checkbox",
name = "another_checkbox",
label = "Another checkbox",
#checked = true
}
}
};
For reference, my "PDItem"s implement the following interfaces:
public interface IDictionaryObject<T>
{
string Key { get; set; }
T Value { get; set; }
}
[JsonConverter(typeof(IItemConverter))]
public interface IItem: IElement
{
}
[JsonConverter(typeof(ElementConverter))]
public interface IElement
{
string elementType { get; }
}
I was able to convert some concrete types (without having to do any tricky dictionary to object conversions), below is a working example of the ElementConverter attacked to my IElement interface (IItem uses the same pattern, and the same JsonCreationConverter class):
public class ElementConverter : JsonCreationConverter<IElement>
{
protected override IElement Create(Type objectType, JObject jObject)
{
//TODO: Add objects to ElementConverter as they come online.
switch (jObject["elementType"].Value<string>())
{
case ElementTypeDescriptions.FirstType:
return new FirstType();
case ElementTypeDescriptions.SecondType:
return new SecondType();
case ElementTypeDescriptions.ThirdType:
return new ThirdType();
case ElementTypeDescriptions.FourthType:
case ElementTypeDescriptions.FifthType:
default:
throw new NotImplementedException("This object type is not yet implemented.");
}
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
try
{
var jObject = JObject.Load(reader);
var target = Create(objectType, jObject);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
catch (JsonReaderException)
{
return null;
}
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
What makes my scenario so tricky is not that I am converting objects to dictionaries and back, but that my object values are other concrete objects (interfaced). I want to write a custom JsonConverter to serialize and deserialize these objects, but have no idea how to read and write the json in the methods below, let alone if what I am attempting to do is even possible. Any assistance would be greatly appreciated!
public class PDItemConverter: JsonConverter<PDItem>
{
public override void WriteJson(JsonWriter writer, PDItem value, JsonSerializer serializer)
{
/// DO STUFF
}
public override PDItem ReadJson(JsonReader reader, Type objectType, PDItem existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
/// DO STUFF
}
}
EDITED PER DBC's request:
Apologies for the complicated question DBC, and I greatly appreciate your time! Obviously, I'm a bit new to posting to stack overflow (long time lurker as they say).
Below is full working code that will run in .net fiddle (or in a console application if you simply add a namespace and json.net 12.x packages to a new .NET 4.7.2 console project). Second apologies that it is still a bit long and complicated, It is actually greatly simplified thanks to the omission of the Validation code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class PDItem : IDictionaryObject<List<IItem>>
{
[JsonProperty]
public string Key { get; set; }
[JsonProperty]
public List<IItem> Value { get; set; }
}
public interface IDictionaryObject<T>
{
string Key { get; set; }
T Value { get; set; }
}
[JsonConverter(typeof(IItemConverter))]
public interface IItem : IElement
{
string itemType { get; }
}
[JsonConverter(typeof(ElementConverter))]
public interface IElement
{
string elementType { get; }
}
public class ElementConverter : JsonCreationConverter<IElement>
{
protected override IElement Create(Type objectType, JObject jObject)
{
//TODO: Add objects to ElementConverter as they come online.
switch (jObject["elementType"].Value<string>())
{
case ElementTypeDescriptions.FirstType:
return new FirstType();
case ElementTypeDescriptions.SecondType:
return new SecondType();
//case ElementTypeDescriptions.ThirdType:
// return new ThirdType();
//case ElementTypeDescriptions.FourthType:
//case ElementTypeDescriptions.FifthType:
default:
throw new NotImplementedException("This object type is not yet implemented.");
}
}
}
public class IItemConverter : JsonCreationConverter<IItem>
{
protected override IItem Create(Type objectType, JObject jObject)
{
switch (jObject["itemType"].Value<string>())
{
case ItemTypeDescriptions.FirstItemType:
return new FirstItemType();
case ItemTypeDescriptions.SecondItemType:
return new SecondItemType();
default:
throw new NotImplementedException("This object type is not yet implemented.");
}
}
}
/// <summary>
/// Used constants rather than an enum to allow for use in switch statements. Provided by third party to us to identify their classes across the API.
/// </summary>
public class ElementTypeDescriptions
{
public const string FirstType = "firstTypeId";
public const string SecondType = "secondTypeId";
public const string ThirdType = "thirdTypeId";
public const string FourthType = "fourthTypeId";
public const string FifthType = "fifthTypeId";
}
/// <summary>
/// Used constants rather than an enum to allow for use in switch statements. Provided by third party to us to identify their classes across the API.
/// </summary>
public class ItemTypeDescriptions
{
public const string FirstItemType = "firstItemTypeId";
public const string SecondItemType = "secondItemTypeId";
}
/*** CONCRETE OBJECTS ***/
public class FirstType : IElement
{
public string elementType { get { return ElementTypeDescriptions.FirstType; } }
public string name { get; set; }
}
public class SecondType : IElement
{
public string elementType { get { return ElementTypeDescriptions.FirstType; } }
public string label { get; set; }
}
public class FirstItemType : IItem
{
public string elementType { get { return ElementTypeDescriptions.FourthType; } }
public string itemType { get { return ItemTypeDescriptions.FirstItemType; } }
public string reference { get; set; }
}
public class SecondItemType : IItem
{
public string elementType { get { return ElementTypeDescriptions.FourthType; } }
public string itemType { get { return ItemTypeDescriptions.FirstItemType; } }
public string database { get; set; }
}
/*** END CONCRETE OBJECTS ***/
public class PDItemConverter : JsonConverter<PDItem>
{
public override void WriteJson(JsonWriter writer, PDItem value, JsonSerializer serializer)
{
/// THIS CODE TO BE WRITTEN TO ANSWER THE QUESTION
/// DO STUFF
throw new NotImplementedException("THIS CODE TO BE WRITTEN TO ANSWER THE QUESTION");
}
public override PDItem ReadJson(JsonReader reader, Type objectType, PDItem existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
/// THIS CODE TO BE WRITTEN TO ANSWER THE QUESTION
/// DO STUFF
throw new NotImplementedException("THIS CODE TO BE WRITTEN TO ANSWER THE QUESTION");
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
try
{
var jObject = JObject.Load(reader);
var target = Create(objectType, jObject);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
catch (JsonReaderException)
{
return null;
}
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
class TestClass
{
public static void Test()
{
var json = GetJson();
var item = JsonConvert.DeserializeObject<PDItem>(json);
var json2 = JsonConvert.SerializeObject(item, Formatting.Indented);
Console.WriteLine(json2);
}
static string GetJson()
{
var json = #"{
""checked"": [
{
""elementType"": ""input"",
""inputType"": ""checkbox"",
""name"": ""another_checkbox"",
""label"": ""Another checkbox"",
""checked"": true
}
]
}
";
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}
One of the easiest ways to write a JsonConverter is to map the object to be serialized to some DTO, then (de)serialize the DTO. Since your PDItem looks like a single dictionary key/value pair and is serialized like a dictionary, the easiest DTO to use would be an actual dictionary, namely Dictionary<string, List<IItem>>.
Thus your PDItemConverter can be written as follows:
public class PDItemConverter: JsonConverter<PDItem>
{
public override void WriteJson(JsonWriter writer, PDItem value, JsonSerializer serializer)
{
// Convert to a dictionary DTO and serialize
serializer.Serialize(writer, new Dictionary<string, List<IItem>> { { value.Key, value.Value } });
}
public override PDItem ReadJson(JsonReader reader, Type objectType, PDItem existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
// Deserialize as a dictionary DTO and map to a PDItem
var dto = serializer.Deserialize<Dictionary<string, List<IItem>>>(reader);
if (dto == null)
return null;
if (dto.Count != 1)
throw new JsonSerializationException(string.Format("Incorrect number of dictionary keys: {0}", dto.Count));
var pair = dto.First();
existingValue = hasExistingValue ? existingValue : new PDItem();
existingValue.Key = pair.Key;
existingValue.Value = pair.Value;
return existingValue;
}
}
Since you are (de)serializing using the incoming serializer any converters associated to nested types such as IItem will get picked up and used automatically.
In addition, in JsonCreationConverter<T> you need to override CanWrite and return false. This causes the serializer to fall back to default serialization when writing JSON as explained in this answer to How to use default serialization in a custom JsonConverter. Also, I don't recommend catching and swallowing JsonReaderException. This exception is thrown when the JSON file itself is malformed, e.g. by being truncated. Ignoring this exception and continuing can occasionally force Newtonsoft to fall into an infinite loop. Instead, propagate the exception up to the application:
public abstract class JsonCreationConverter<T> : JsonConverter
{
// Override CanWrite and return false
public override bool CanWrite { get { return false; } }
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var target = Create(objectType, jObject);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Demo fiddle here.
In my API I would like to give consumers the option to send a property as either a string identifier or an object, for example:
{
"source": "token_xyz"
}
Or
{
"source": {
"name": "test"
}
}
Depending on the the type (string or object) I'd like to set a specific property on my class:
public class MyRequest
{
[JsonProperty("source")]
public SourceUser SourceUser { get; set; }
[JsonProperty("source")]
public string SourceToken { get; set; }
}
As you can see, I tried decorating both properties with JsonProperty("source") but unfortunately this does not work - the object fails to deserialize.
How can I deserialize to the appropriate property based on the JSON type?
Json.NET does not support having two properties with the same contract property name, possibly because, as explained in the JSON RFC:
An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable.
Thus you will need some sort of custom JsonConverter to deserialize your "source" property. One easy way to do this is to apply the converter to a private Source property that sets & gets either SourceUser or SourceToken as appropriate:
public class MyRequest
{
[JsonConverter(typeof(SourceConverter))]
[JsonProperty]
object Source
{
get
{
// Possibly throw an exception if both are non-null?
return SourceUser ?? (object)SourceToken;
}
set
{
SourceUser = value as SourceUser;
SourceToken = value as string;
}
}
[JsonIgnore]
public SourceUser SourceUser { get; set; }
[JsonIgnore]
public string SourceToken { get; set; }
}
class SourceConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException("This converter is intended to be applied with [JsonConverter(typeof(SourceConverter))]");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType == JsonToken.StartObject)
return serializer.Deserialize<SourceUser>(reader);
else
return (string)JValue.Load(reader);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Sample fiddle.
I'm using WebAPI, which relies on JSON .NET for the JSON format. On the C# side I have a DTO that looks like this:
public class DTO1 : IManifestContainer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public HashSet<string> Manifest { get; private set; }
}
public interface IManifestContainer
{
HashSet<string> Manifest { get; }
}
The idea of the IManifestContainer interface is to keep track of the properties that the client is actually sending to the server in the JSON object. For example, if the client sends this JSON:
{"FirstName":"Jojo"}
The Manifest hashset will contain the "FirstName" only.
If the client sends:
{"FirstName":"Jojo", "LastName":"Jones"}
The Manifest hashset will contain both "FirstName" and "LastName".
I tried implementing a JsonConverter like this:
public class ManifestJsonConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
JObject jObject = JObject.Load(reader);
// Convert the JObject to a C# object??
// Passing the serializer will call this method again
object retVal = jObject.ToObject(objectType, serializer);
IManifestContainer manifestContainer = (IManifestContainer) retVal;
foreach (var jProperty in jObject.Properties())
{
manifestContainer.Manifest.Add(jProperty.Name);
}
return retVal;
}
public override bool CanConvert(Type objectType)
{
return typeof (IManifestContainer).IsAssignableFrom(objectType);
}
}
I need to load the JObject to obtain all the properties coming from the client, but then I don't know how to create the instance of "objectType" (the C# DTO) from the JObject.
After reading this other post I came up with this implementation. This covers all cases.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
JObject jObject = JObject.Load(reader);
JArray manifestArray = new JArray();
foreach (var jProperty in jObject.Properties())
{
manifestArray.Add(jProperty.Name);
}
jObject["Manifest"] = manifestArray;
var retVal = Activator.CreateInstance(objectType);
serializer.Populate(jObject.CreateReader(), retVal);
return retVal;
}
You can try using the overload of JObject.ToObject that does not take a JsonSerializer. In that case the ToObject method will use a new serializer instance that does not know about the converter, which should allow it to work, as long as you have not decorated your DTO classes with [JsonConverter] attributes.
object retVal = jObject.ToObject(objectType);
If that doesn't work, your other option is to create the DTO instances manually and populate their properties via reflection.
When using Json.Net, I understand how to get the $type property into the rendered json, but is there a way to change that field name? I need to use "__type" instead of "$type".
http://json.codeplex.com/workitem/22429
"I would rather keep $type hard coded and consistent."
Consistent with what I wonder?
http://json.codeplex.com/workitem/21989
I would rather not - I think this is too specific to me and I don't
want to go overboard with settings. At some point I will probably
implement this - http://json.codeplex.com/workitem/21856 - allowing
people to read/write there own meta properties in the JSON and you
could reimplement type name handling with a new property name. The
other option is just to modify the source code for yourself to have
that property name.
And more recently, Issue #36: Customizable $type property name feature:
I'd rather not
This is my solution...
json.Replace("\"$type\": \"", "\"type\": \"");
Looks like this is hardcoded as public const string TypePropertyName = "$type"; in Newtonsoft.Json.Serialization.JsonTypeReflector which is internal static class unfortunately.
I needed this myself, and the only thing I can think of is having custom modified version of json.net itself. Which is of course is a major pita.
when serializing, there is a nice way to override the property name:
public class CustomJsonWriter : JsonTextWriter
{
public CustomJsonWriter(TextWriter writer) : base(writer)
{
}
public override void WritePropertyName(string name, bool escape)
{
if (name == "$type") name = "__type";
base.WritePropertyName(name, escape);
}
}
var serializer = new JsonSerializer();
var writer = new StreamWriter(stream) { AutoFlush = true };
serializer.Serialize(new CustomJsonWriter(writer), objectToSerialize);
I haven't tried deserialization yet, but in worst case I could use:
json.Replace("\"__type": \"", "\"type\": \"$type\");
I had to do this for my UI REST API as Angular.js disregards fields names starting with a dollar sign ($).
So here's a solution that renames $type to __type for the whole Web API and works both for serialization and deserialization.
In order to be able to use a custom JsonWriter and a custom JsonReader (as proposed in the other answers to this question), we have to inherit the JsonMediaTypeFormatter and override the corresponding methods:
internal class CustomJsonNetFormatter : JsonMediaTypeFormatter
{
public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding)
{
return new CustomJsonReader(readStream, effectiveEncoding);
}
public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)
{
return new CustomJsonWriter(writeStream, effectiveEncoding);
}
private class CustomJsonWriter : JsonTextWriter
{
public CustomJsonWriter(Stream writeStream, Encoding effectiveEncoding)
: base(new StreamWriter(writeStream, effectiveEncoding))
{
}
public override void WritePropertyName(string name, bool escape)
{
if (name == "$type") name = "__type";
base.WritePropertyName(name, escape);
}
}
private class CustomJsonReader : JsonTextReader
{
public CustomJsonReader(Stream readStream, Encoding effectiveEncoding)
: base(new StreamReader(readStream, effectiveEncoding))
{
}
public override bool Read()
{
var hasToken = base.Read();
if (hasToken && TokenType == JsonToken.PropertyName && Value != null && Value.Equals("__type"))
{
SetToken(JsonToken.PropertyName, "$type");
}
return hasToken;
}
}
}
Of course you need to register the custom formatter in your WebApiConfig. So we replace the default Json.NET formatter with our custom one:
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.Add(new CustomJsonNetFormatter());
Done.
We had a need for this so I created a custom JsonReader. We're are using rest in our MS web services with complex data models and needed to replace the "__type" property with "$type."
class MSJsonReader : JsonTextReader
{
public MSJsonTextReader(TextReader reader) : base(reader) { }
public override bool Read()
{
var hasToken = base.Read();
if (hasToken && base.TokenType == JsonToken.PropertyName && base.Value != null && base.Value.Equals("__type"))
base.SetToken(JsonToken.PropertyName, "$type");
return hasToken;
}
}
Here is how we use it.
using(JsonReader jr = new MSJsonTextReader(sr))
{
JsonSerializer s = new JsonSerializer();
s.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
s.NullValueHandling = NullValueHandling.Ignore;
s.TypeNameHandling = TypeNameHandling.Auto; // Important!
s.Binder = new MSRestToJsonDotNetSerializationBinder("Server.DataModelsNamespace", "Client.GeneratedModelsNamespace");
T deserialized = s.Deserialize<T>(jr);
return deserialized;
}
Here is our MSRestToJsonDotNetSerializationBinder that completes the compatibility between MS rest and Json.Net.
class MSRestToJsonDotNetSerializationBinder : System.Runtime.Serialization.SerializationBinder
{
public string ServiceNamespace { get; set; }
public string LocalNamespace { get; set; }
public MSRestToJsonDotNetSerializationBinder(string serviceNamespace, string localNamespace)
{
if (serviceNamespace.EndsWith("."))
serviceNamespace = serviceNamespace.Substring(0, -1);
if(localNamespace.EndsWith("."))
localNamespace = localNamespace.Substring(0, -1);
ServiceNamespace = serviceNamespace;
LocalNamespace = localNamespace;
}
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
assemblyName = null;
typeName = string.Format("{0}:#{1}", serializedType.Name, ServiceNamespace); // MS format
}
public override Type BindToType(string assemblyName, string typeName)
{
string jsonDotNetType = string.Format("{0}.{1}", LocalNamespace, typeName.Substring(0, typeName.IndexOf(":#")));
return Type.GetType(jsonDotNetType);
}
}
You could also do it this way:
[JsonConverter(typeof(JsonSubtypes), "ClassName")]
public class Annimal
{
public virtual string ClassName { get; }
public string Color { get; set; }
}
You will need the JsonSubtypes
converter that is not part of Newtonsoft.Json project.
There is another option that allows to serialize custom type property name in Json.NET. The idea is do not write default $type property, but introduce type name as property of class itself.
Suppose we have a Location class:
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
First, we need to introduce type property name and modify the class as demonstrated below:
public class Location
{
[JsonProperty("__type")]
public string EntityTypeName
{
get
{
var typeName = string.Format("{0}, {1}", GetType().FullName, GetType().Namespace);
return typeName;
}
}
public double Latitude { get; set; }
public double Longitude { get; set; }
}
Then, set JsonSerializerSettings.TypeNameHandling to TypeNameHandling.None in order the deserializer to skip the rendering of default $type attribute.
That's it.
Example
var point = new Location() { Latitude = 51.5033630, Longitude = -0.1276250 };
var jsonLocation = JsonConvert.SerializeObject(point, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.None, //do not write type property(!)
});
Console.WriteLine(jsonLocation);
Result
{"__type":"Namespace.Location, Namespace","Latitude":51.503363,"Longitude":-0.127625}
Using a custom converter should get the job done.
public CustomConverter : JsonConverter
{
public override bool CanWrite => true;
public override bool CanRead => true;
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
=> throw new NotImplementedException();
public override void WriteJson(JsonWriter writer,
object value,
JsonSerializer serializer)
{
var jOjbect = (JObject)JToken.FromObject(value);
jOjbect.Add(new JProperty("type", value.GetType().Name));
jOjbect.WriteTo(writer);
}
}