How to serialize a collection (with an indexer property) as a dictionary - c#

I have a class, FooCollection let's say, which implements IEnumerable<Foo>, and also provides an indexer by which one can look up a Foo by its name. Functionally it's read-only as a dictionary. But it's not really a dictionary because users do not get to decide on the keys.
Anyway, I want JSON.NET to serialize this object as a JSON dictionary, instead of as an array, which it's doing now. Sticking JsonDictionaryAttribute on it doesn't work: then it does nothing.
Clues?

You're probably going to need to create a custom JsonConverter for your FooCollection class in order to serialize it the way you want. Since you haven't posted any code at all, I'll just make something up for sake of example. Let's say your Foo and FooCollection classes look like this:
class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
class FooCollection : IEnumerable<Foo>
{
private List<Foo> list = new List<Foo>();
public void Add(Foo foo)
{
list.Add(foo);
}
public Foo this[string name]
{
get { return list.Find(f => f.Name == name); }
}
public IEnumerator<Foo> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)list).GetEnumerator();
}
}
The following converter would serialize the FooCollection as if it were a dictionary. I'm assuming that you would want the converter to use the value of the Name property as the key for each Foo for purposes of serialization (to match the indexer on the collection), so that is how I implemented it. You can change it to something else by modifying the GetFooKey() method.
class FooCollectionConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(FooCollection));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject();
foreach (Foo foo in (FooCollection)value)
{
writer.WritePropertyName(GetFooKey(foo));
serializer.Serialize(writer, foo);
}
writer.WriteEndObject();
}
// Given a Foo, return its unique key to be used during serialization
private string GetFooKey(Foo foo)
{
return foo.Name;
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Here is an example program that demonstrates how to use the converter.
class Program
{
static void Main(string[] args)
{
FooCollection coll = new FooCollection();
coll.Add(new Foo { Id = 1, Name = "Moe" });
coll.Add(new Foo { Id = 2, Name = "Larry" });
coll.Add(new Foo { Id = 3, Name = "Curly" });
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new FooCollectionConverter());
settings.Formatting = Newtonsoft.Json.Formatting.Indented;
string json = JsonConvert.SerializeObject(coll, settings);
Console.WriteLine(json);
}
}
And here is the output of the above program:
{
"Moe": {
"Id": 1,
"Name": "Moe"
},
"Larry": {
"Id": 2,
"Name": "Larry"
},
"Curly": {
"Id": 3,
"Name": "Curly"
}
}
Fiddle: https://dotnetfiddle.net/wI2iQG

Related

JSON to C#, deserialize property that is either object or array

I have an issue with handling JSON data from an api that I use in my application. The problem is that the JSON contains some properties that are an object when there is an item, and become an array when there are more items. So that's a structure like this:
[
{
"MyObj": {
"Foo": "Bar"
}
},
{
"MyObj": [
{
"Foo": "Bar1"
},
{
"Foo": "Bar2"
}
]
}
]
I've tried several JSON to C# converters, some of them generate a property of type object, the quicktype.io converter generates this:
public class Example
{
[JsonProperty("MyObj")]
public MyObjUnion MyObj { get; set; }
}
public partial class MyObjElement
{
[JsonProperty("Foo")]
public string Foo { get; set; }
}
public struct MyObjUnion
{
public MyObjElement MyObjElement;
public MyObjElement[] MyObjElementArray;
public static implicit operator MyObjUnion(MyObjElement MyObjElement) => new MyObjUnion { MyObjElement = MyObjElement };
public static implicit operator MyObjUnion(MyObjElement[] MyObjElementArray) => new MyObjUnion { MyObjElementArray = MyObjElementArray };
}
internal class MyObjUnionConverter : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(MyObjUnion) || t == typeof(MyObjUnion?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.StartObject:
var objectValue = serializer.Deserialize<MyObjElement>(reader);
return new MyObjUnion { MyObjElement = objectValue };
case JsonToken.StartArray:
var arrayValue = serializer.Deserialize<MyObjElement[]>(reader);
return new MyObjUnion { MyObjElementArray = arrayValue };
}
throw new Exception("Cannot unmarshal type MyObjUnion");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
var value = (MyObjUnion)untypedValue;
if (value.MyObjElementArray != null)
{
serializer.Serialize(writer, value.MyObjElementArray);
return;
}
if (value.MyObjElement != null)
{
serializer.Serialize(writer, value.MyObjElement);
return;
}
throw new Exception("Cannot marshal type MyObjUnion");
}
public static readonly MyObjUnionConverter Singleton = new MyObjUnionConverter();
}
Although this does work correctly, it's still a bit cumbersome because to get the data you always need to check if it's in the MyObjElement or MyObjElementArray class.
So the question is if there are other, more elegant ways to solve this issue. (Other than changing the API output, which is not mine)
If you know the data structure before hand, I would create a custom data model for the Json file and then deserialise it like so:
CurrencyExchangeRates deserialisedData = JsonConvert.DeserializeObject<CurrencyExchangeRates>(savedData);
foreach (CurrentRate value in deserialisedData.ExchangeRates)
{
rate.ExchangeRates.Add(new CurrentRate { Rate = value.Rate, Timestamp = value.Timestamp });
}
This is how I did that in an application. Hope this helps a little.
You can check and cast each object in your JSON depending the type of object.
For example consider using Newtonsoft.Json library for JSON parsing, you can do the following:
// considering your JSON string
string jsonString = "[{'MyObj':{'Foo':'Bar'}},{'MyObj':[{'Foo':'Bar1'},{'Foo':'Bar2'}]}]";
// parse your JSON into JTokens
var tokens = JToken.Parse(jsonString);
// iterate through all the tokens
foreach (var token in tokens)
{
// your token is a grand child
JToken myObj = token.First.First;
// check if the grand child is array
if (myObj is JArray)
{
// cast the grand child token into MyObj list or array object
IEnumerable<MyObj> objList = myObj.ToObject<List<MyObj>>();
Console.WriteLine("converted to MyObj Array");
}
else if (myObj is JObject) // else if its a non array item
{
// cast the grand child token into MyObj object
MyObj obj = myObj.ToObject<MyObj>();
Console.WriteLine("converted to MyObj");
}
}
// your MyObj Type will look like this:
public class MyObj
{
public string Foo { get; set; }
}

Is there a way to use Json.Net to deserialize some json which calls a method to add the items to a collection (there is no property setter)

I have a class that has a collection which is readonly and has no setter.
Is there a way to de-serialize some json and get it call a method on the instance instead of the property setter?
For example:
public class User
{
private ObservableCollection<Movie> _movies;
public string Name { get; set; }
public ReadOnlyCollection<Movie> FavouriteMovies { get; set; }
public void AddMovie(Movie movie) { .. }
//-or-
public void AddMovies(IEnumerable<Movie> movies){ .. }
}
The only way to get things into the _movies backing field is via the method AddMovies. So when trying to deserialize some valid json which has an array of Movies in the json, it will call AddMovie or AddMovies...
Ninja update by PK:
I've forked the fiddle below using a collection of classes instead of simple strings, for a more complex example that now works, based on the answer below.
Use a JsonConverter to do custom conversion of your json. Here's a simple example of how that might work. Given a class like this:
public class MyClass
{
private List<string> backingField;
public string Name { get; set; }
public IReadOnlyCollection<string> MyStrings { get; private set; }
public MyClass()
{
backingField = new List<string>();
MyStrings = backingField.AsReadOnly();
}
public void AddString(string item)
{
backingField.Add(item);
}
}
And JSON like this:
{
"MyStrings": [
"Foo",
"Bar"
],
"Name":"My stuff"
}
You could create a converter to read that json and call AddString to populate the backingField like this:
public class MyClassConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = new MyClass();
var jObj = JObject.Load(reader);
JsonConvert.PopulateObject(jObj.ToString(), obj); // populate fields we don't need any special handling for
var stringsProp = jObj["MyStrings"];
if (stringsProp != null)
{
var strings = stringsProp.ToObject<List<string>>();
foreach (var s in strings)
{
obj.AddString(s);
}
}
return obj;
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MyClass);
}
}
Now to use it, and keep MyClass ignorant of how it get deserialized, you can simply do something like this:
var m = JsonConvert.DeserializeObject(json, typeof(MyClass), new MyClassConverter()) as MyClass;
Here's a fiddle

Custom JsonConverter WriteJson Does Not Alter Serialization of Sub-properties

I always had the impression that the JSON serializer actually traverses your entire object's tree, and executes the custom JsonConverter's WriteJson function on each interface-typed object that it comes across - not so.
I have the following classes and interfaces:
public interface IAnimal
{
string Name { get; set; }
string Speak();
List<IAnimal> Children { get; set; }
}
public class Cat : IAnimal
{
public string Name { get; set; }
public List<IAnimal> Children { get; set; }
public Cat()
{
Children = new List<IAnimal>();
}
public Cat(string name="") : this()
{
Name = name;
}
public string Speak()
{
return "Meow";
}
}
public class Dog : IAnimal
{
public string Name { get; set; }
public List<IAnimal> Children { get; set; }
public Dog()
{
Children = new List<IAnimal>();
}
public Dog(string name="") : this()
{
Name = name;
}
public string Speak()
{
return "Arf";
}
}
To avoid the $type property in the JSON, I've written a custom JsonConverter class, whose WriteJson is
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
IAnimal animal = value as IAnimal;
JObject o = (JObject)t;
if (animal != null)
{
if (animal is Dog)
{
o.AddFirst(new JProperty("type", "Dog"));
//o.Find
}
else if (animal is Cat)
{
o.AddFirst(new JProperty("type", "Cat"));
}
foreach(IAnimal childAnimal in animal.Children)
{
// ???
}
o.WriteTo(writer);
}
}
}
In this example, yes, a dog can have cats for children and vice-versa. In the converter, I want to insert the "type" property so that it saves that to the serialization. I have the following setup. (Zoo has only a name and a list of IAnimals. I didn't include it here for brevity and laziness ;))
Zoo hardcodedZoo = new Zoo()
{ Name = "My Zoo",
Animals = new List<IAnimal> { new Dog("Ruff"), new Cat("Cleo"),
new Dog("Rover"){
Children = new List<IAnimal>{ new Dog("Fido"), new Dog("Fluffy")}
} }
};
JsonSerializerSettings settings = new JsonSerializerSettings(){
ContractResolver = new CamelCasePropertyNamesContractResolver() ,
Formatting = Formatting.Indented
};
settings.Converters.Add(new AnimalsConverter());
string serializedHardCodedZoo = JsonConvert.SerializeObject(hardcodedZoo, settings);
serializedHardCodedZoo has the following output after serialization:
{
"name": "My Zoo",
"animals": [
{
"type": "Dog",
"Name": "Ruff",
"Children": []
},
{
"type": "Cat",
"Name": "Cleo",
"Children": []
},
{
"type": "Dog",
"Name": "Rover",
"Children": [
{
"Name": "Fido",
"Children": []
},
{
"Name": "Fluffy",
"Children": []
}
]
}
]
}
The type property shows up on Ruff, Cleo, and Rover, but not for Fido and Fluffy. I guess the WriteJson isn't called recursively. How do I get that type property there?
As an aside, why does it not camel-case IAnimals like I expect it to?
The reason that your converter is not getting applied to your child objects is because JToken.FromObject() uses a new instance of the serializer internally, which does not know about your converter. There is an overload that allows you to pass in the serializer, but if you do so here you will have another problem: since you are inside a converter and you are using JToken.FromObject() to try to serialize the parent object, you will get into an infinite recursive loop. (JToken.FromObject() calls the serializer, which calls your converter, which calls JToken.FromObject(), etc.)
To get around this problem, you must handle the parent object manually. You can do this without much trouble using a bit of reflection to enumerate the parent properties:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JObject jo = new JObject();
Type type = value.GetType();
jo.Add("type", type.Name);
foreach (PropertyInfo prop in type.GetProperties())
{
if (prop.CanRead)
{
object propVal = prop.GetValue(value, null);
if (propVal != null)
{
jo.Add(prop.Name, JToken.FromObject(propVal, serializer));
}
}
}
jo.WriteTo(writer);
}
Fiddle: https://dotnetfiddle.net/sVWsE4
Here's an idea, instead of doing the reflection on every property, iterate through the normally serialized JObject and then changed the token of properties you're interested in.
That way you can still leverage all the ''JsonIgnore'' attributes and other attractive features built-in.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken jToken = JToken.FromObject(value);
if (jToken.Type == JTokenType.Object)
{
JObject jObject = (JObject)jToken;
...
AddRemoveSerializedProperties(jObject, val);
...
}
...
}
And then
private void AddRemoveSerializedProperties(JObject jObject, MahMan baseContract)
{
jObject.AddFirst(....);
foreach (KeyValuePair<string, JToken> propertyJToken in jObject)
{
if (propertyJToken.Value.Type != JTokenType.Object)
continue;
JToken nestedJObject = propertyJToken.Value;
PropertyInfo clrProperty = baseContract.GetType().GetProperty(propertyJToken.Key);
MahMan nestedObjectValue = clrProperty.GetValue(baseContract) as MahMan;
if(nestedObj != null)
AddRemoveSerializedProperties((JObject)nestedJObject, nestedObjectValue);
}
}
I had this issue using two custom converters for a parent and child type. A simpler method I found is that since an overload of JToken.FromObject() takes a serializer as a parameter, you can pass along the serializer you were given in WriteJson(). However you need to remove your converter from the serializer to avoid a recursive call to it (but add it back in after):
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Converters.Remove(this);
JToken jToken = JToken.FromObject(value, serializer);
serializer.Converters.Add(this);
// Perform any necessary conversions on the object returned
}
Here is a hacky solution to your problem that gets the work done and looks tidy.
public class MyJsonConverter : JsonConverter
{
public const string TypePropertyName = "type";
private bool _dormant = false;
/// <summary>
/// A hack is involved:
/// " JToken.FromObject(value, serializer); " creates amn infinite loop in normal circumstances
/// for that reason before calling it "_dormant = true;" is called.
/// the result is that this JsonConverter will reply false to exactly one "CanConvert()" call.
/// this gap will allow to generate a a basic version without any extra properties, and then add them on the call with " JToken.FromObject(value, serializer); ".
/// </summary>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
_dormant = true;
JToken t = JToken.FromObject(value, serializer);
if (t.Type == JTokenType.Object && value is IContent)
{
JObject o = (JObject)t;
o.AddFirst(new JProperty(TypePropertyName, value.GetType().Name));
o.WriteTo(writer);
}
else
{
t.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead => false;
public override bool CanConvert(Type objectType)
{
if (_dormant)
{
_dormant = false;
return false;
}
return true;
}
}

WebAPI JSON Serialization not serializing any children of a composite object

So I am needing to serialize a composite to JSON (with JSON.NET) and was hoping that coming here with this problem would be a quick win.
I have a very basic composite implementation that I am just trying to use to scaffold my services and the data structure but the JSONSerializer is only serializing the root node.
Code:
namespace Data
{
public abstract class Element
{
protected string _name;
public Element(string name)
{
_name = name;
}
public abstract void Add(Element element);
public string Name { get { return _name; } }
}
public class ConcreteElement : Element
{
public ConcreteElement(string name) : base(name) { }
public override void Add(Element element)
{
throw new InvalidOperationException("ConcreteElements may not contain Child nodes. Perhaps you intended to add this to a Composite");
}
}
public class Composite: Element
{
public Composite(string name) : base(name) { Elements = new List<Element>(); }
private List<Element> Elements { get; set; }
public override void Add(Element element)
{
Elements.Add(element);
}
}
}
In my Controller's HttpGet method,
Composite root = new Composite("Root");
Composite branch = new Composite("Branch");
branch.Add(new ConcreteElement("Leaf1"));
branch.Add(new ConcreteElement("Leaf2"));
root.Add(branch);
return JsonConvert.SerializeObject(root);
And the only thing that is being serialized is
{"Name\":\"Root\"}"
Can anyone see a reason that this is not serializing child elements?
I'm hoping it's something stupid.
Edit1
I've never tried to Serialize a graph to JSON with WebAPI before. Do I need to write a custom MediaTypeFormatter for serializing this?
Edit2 (to add desired output)
Leaf1 and Leaf2 are just markers at the moment. They will themselves be complex objects once I can get this to serialize.
So, at the moment...
{
"Name" : "Root"
,"Branch":
[
{"Name":"Leaf1"}
,{"Name":"Leaf2"}
]
]
}
and eventually
{
"Name" : "Root"
,"Branch1":
[
{"Name":"Leaf1", "Foo":"Bar"}
{"Name":"Leaf2", "Foo":"Baz"}
]
,"Branch2":
[
"Branch3":[
{"Name":"Leaf3", "Foo":"Quux"}
]
]
}
The children are not being serialized because the list of Elements in your Composite is private. Json.Net will not serialize private members by default. If you mark the list with [JsonProperty("Elements")] then the children will be serialized.
public class Composite: Element
{
...
[JsonProperty("Elements")]
private List<Element> Elements { get; set; }
...
}
If you run your example code with this change, you should get the following JSON:
{
"Elements": [
{
"Elements": [
{
"Name": "Leaf1"
},
{
"Name": "Leaf2"
}
],
"Name": "Branch"
}
],
"Name": "Root"
}
EDIT
OK, here is an example converter for your composite:
class CompositeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Composite));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Composite composite = (Composite)value;
// Need to use reflection here because Elements is private
PropertyInfo prop = typeof(Composite).GetProperty("Elements", BindingFlags.NonPublic | BindingFlags.Instance);
List<Element> children = (List<Element>)prop.GetValue(composite);
JArray array = new JArray();
foreach (Element e in children)
{
array.Add(JToken.FromObject(e, serializer));
}
JObject obj = new JObject();
obj.Add(composite.Name, array);
obj.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Here is a demo:
class Program
{
static void Main(string[] args)
{
Composite root = new Composite("Root");
Composite branch1 = new Composite("Branch1");
branch1.Add(new ConcreteElement("Leaf1", "Bar"));
branch1.Add(new ConcreteElement("Leaf2", "Baz"));
root.Add(branch1);
Composite branch2 = new Composite("Branch2");
branch2.Add(new ConcreteElement("Leaf3", "Quux"));
Composite branch3 = new Composite("Branch3");
branch3.Add(new ConcreteElement("Leaf4", "Fizz"));
branch2.Add(branch3);
root.Add(branch2);
string json = JsonConvert.SerializeObject(root, Formatting.Indented, new CompositeConverter());
Console.WriteLine(json);
}
}
public abstract class Element
{
protected string _name;
public Element(string name)
{
_name = name;
}
public abstract void Add(Element element);
public string Name { get { return _name; } }
}
public class ConcreteElement : Element
{
public ConcreteElement(string name, string foo) : base(name)
{
Foo = foo;
}
public string Foo { get; set; }
public override void Add(Element element)
{
throw new InvalidOperationException("ConcreteElements may not contain Child nodes. Perhaps you intended to add this to a Composite");
}
}
public class Composite : Element
{
public Composite(string name) : base(name) { Elements = new List<Element>(); }
private List<Element> Elements { get; set; }
public override void Add(Element element)
{
Elements.Add(element);
}
}
Here is the resulting JSON output:
{
"Root": [
{
"Branch1": [
{
"Foo": "Bar",
"Name": "Leaf1"
},
{
"Foo": "Baz",
"Name": "Leaf2"
}
]
},
{
"Branch2": [
{
"Foo": "Quux",
"Name": "Leaf3"
},
{
"Branch3": [
{
"Foo": "Fizz",
"Name": "Leaf4"
}
]
}
]
}
]
}
I realize that this is not exactly the same JSON that you asked for, but it should get you going in the right direction. One problem with the "desired" JSON you specified in your question is that it is not entirely valid. Named properties can only be inside an object, not directly inside an array. In your second example, you have a named "Branch3" property directly inside the array for "Branch2". This won't work. So, you would need to make Branch2 an object instead. But if you do this, then you have an inconsistent representation for your composite: if it contains only leaves, then it is an array, otherwise it is an object. It is possible to make a converter to change the representation of the composite based on the contents (in fact I managed to create such a beast), but that makes the JSON more difficult to consume, and in the end I don't think you'll want to use it. In case you're curious, I've included this alternate converter below, along with its output.
class CompositeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Composite));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Composite composite = (Composite)value;
// Need to use reflection here because Elements is private
PropertyInfo prop = typeof(Composite).GetProperty("Elements", BindingFlags.NonPublic | BindingFlags.Instance);
List<Element> children = (List<Element>)prop.GetValue(composite);
// if all children are leaves, output as an array
if (children.All(el => el.GetType() != typeof(Composite)))
{
JArray array = new JArray();
foreach (Element e in children)
{
array.Add(JToken.FromObject(e, serializer));
}
array.WriteTo(writer);
}
else
{
// otherwise use an object
JObject obj = new JObject();
if (composite.Name == "Root")
{
obj.Add("Name", composite.Name);
}
foreach (Element e in children)
{
obj.Add(e.Name, JToken.FromObject(e, serializer));
}
obj.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Output using the same data:
{
"Name": "Root",
"Branch1": [
{
"Foo": "Bar",
"Name": "Leaf1"
},
{
"Foo": "Baz",
"Name": "Leaf2"
}
],
"Branch2": {
"Leaf3": {
"Foo": "Quux",
"Name": "Leaf3"
},
"Branch3": [
{
"Foo": "Fizz",
"Name": "Leaf4"
}
]
}
}
If you don't want to use Datacontract , i think you have to implement JsonConverter with some the methodes that you need.
namespace JsonOutil
{
public class TestConverter<T> : JsonConverter
{
public override bool CanConvert(System.Type objectType)
{
return objectType == typeof(yourClasse);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object retVal = new Object();
if (reader.TokenType == JsonToken.StartObject)
{
T instance = (T)serializer.Deserialize(reader, typeof(T));
retVal = new List<T>() { instance };
}
else if (reader.TokenType == JsonToken.StartArray)
{
retVal = serializer.Deserialize(reader, objectType);
}
return retVal;
}
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
{
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new System.NotImplementedException();
}
public string GetValueWhenReading(Dictionary<string, object> values, string key)
{
return !values.ContainsKey(key) || values[key] == null
? null
: values[key].ToString();
}
}
}

Run default serialization logic from JsonConverter

I have a JsonConverter that, depending on an instance specific flag, needs to either
run custom serialization logic
run the default Json.NET serialization logic
How can the default Json.NET serialization logic be ran from a JsonConverter?
Thanks
Here is an example. Say your class to serialize looks like this:
class Foo
{
public bool IsSpecial { get; set; }
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
The IsSpecial flag is used to control whether we do something special in the converter or just let things serialize naturally. You can write your converter like this:
class FooConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Foo).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Foo foo = (Foo)value;
JObject jo;
if (foo.IsSpecial)
{
// special serialization logic based on instance-specific flag
jo = new JObject();
jo.Add("names", string.Join(", ", new string[] { foo.A, foo.B, foo.C }));
}
else
{
// normal serialization
jo = JObject.FromObject(foo);
}
jo.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, to use the converter, pass an instance of it to the SerializeObject method (e.g. in the settings). (Do NOT decorate the target class with a JsonConverter attribute, or this will result in an infinite recursive loop when you serialize.)
class Program
{
static void Main(string[] args)
{
List<Foo> foos = new List<Foo>
{
new Foo
{
A = "Moe",
B = "Larry",
C = "Curly",
IsSpecial = false
},
new Foo
{
A = "Huey",
B = "Dewey",
C = "Louie",
IsSpecial = true
},
};
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new FooConverter());
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(foos, settings);
Console.WriteLine(json);
}
}
Output:
[
{
"IsSpecial": false,
"A": "Moe",
"B": "Larry",
"C": "Curly"
},
{
"names": "Huey, Dewey, Louie"
}
]
You can change the CanWrite property to disable a custom serializer. This won't work right if the object can contain children of the same type or if you are serializing in more than one thread.
class FooConverter : JsonConverter
{
bool _canWrite = true;
public override bool CanWrite
{
get { return _canWrite;}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Foo foo = (Foo)value;
JObject jo;
if (foo.IsSpecial)
{
// special serialization logic based on instance-specific flag
jo = new JObject();
jo.Add("names", string.Join(", ", new string[] { foo.A, foo.B, foo.C }));
}
else
{
// normal serialization
_canWrite = false;
jo = JObject.FromObject(foo);
_canWrite = true;
}
jo.WriteTo(writer);
}
}

Categories

Resources