Newtonsoft JsonConverter to convert a string or object to object - c#

I have a requirement for some deserialization I'm trying to handle where I could have these potential inputs:
{
"value": "a string"
}
-- or --
{
"value": {
"text": "a string"
// there are other properties, but for successful deserialization I only need text present
}
}
And I expect it to be able to successfully convert to the object, MyObject:
public class MyObject
{
[JsonProperty("text")
public string Text { get; set; }
}
So far this is what I have in my converter. This case works fine when it's a string (although not very efficient because I'm throwing an exception to catch a failed deserialization). However, when it's an object the reader throws an exception and I'm uncertain of how to handle it.
public class MyObjectConverter : JsonConverter
{
public override bool CanWrite { get => false; }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string) || objectType == typeof(MyObject);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = reader.Value?.ToString();
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
try
{
return JObject.Parse(value).ToObject<MyObject>();
}
catch (Exception)
{
return new MyObject
{
Text = value
};
}
}
}
perhaps I'm there is already a nice way to do this that I'm unaware of? If not, how can I determine whether my input is a string or an object to be able to return the object I care about?
SOLUTION:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
return new MyObject
{
Text = reader.Value?.ToString()
};
}
else if (reader.TokenType == JsonToken.StartObject)
{
JObject obj = JObject.Load(reader);
return obj.ToObject<MyObject>();
}
else
{
return null;
}
}

Your Object isn't structured like the input your expecting. For the second case, MyObject would need to look like this:
// this is ugly
public class MyObject
{
public Value value{get;set;}
public class Value{
public string text {get;set;}
}
}
If you want to have just an object with a single Text property like you currently do, you could do something like this:
public override object ReadJson(JsonReader reader, Type objectType, object
existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
var value = obj["value"];
if(value is JObject) // this will be true if the value property is a nested structure
return new MyObject(){Text=value["text"]}; // could also do value.ToObject<MyObject>() if you need more properties
else
return new MyObject(){Text=value};
}

Related

Deserialize inconsistent JSON property

Hopefully someone can help me with the following inconsistency occurring in a large JSON file that I am attempting to deserialize using Newtonsoft.Json.
One of the properties of the object occasionally appears as:
"roles": [
{
"field1" : "value",
"field2" : "value"
}
]
While other times that same property appears as:
"roles": {
"roles": [
{
"field1" : "value",
"field2" : "value"
}
]
}
For reference, this property is implemented in its class as:
[JsonProperty("roles")]
public List<Role> Roles { get; set; }
What I need to happen is that whenever the second situation above occurs, the object contents are deserialized like the first situation. i.e. the "outer" object is discarded/ignored
I have managed to handle another inconsistency in this file when a separate property sometimes occurs as an object and sometimes as an array using the following approach in its class definition:
[JsonConverter(typeof(SingleValueArrayConverter<Address>))]
public List<Address> Location { get; set; }
And implemented as:
public class SingleValueArrayConverter<T> : 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)
{
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 bool CanConvert(Type objectType)
{
return true;
}
}
However, I am unable to work out this issue.
Can anyone help?
You can handle this inconsistency with a JsonConverter also. It will be a little different than the one you have, but the idea is very similar:
public class ArrayOrWrappedArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(List<T>).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return CreateListFromJArray((JArray)token, serializer);
}
if (token.Type == JTokenType.Object)
{
JObject wrapper = (JObject)token;
JProperty prop = wrapper.Properties().FirstOrDefault();
if (prop.Value.Type == JTokenType.Array)
{
return CreateListFromJArray((JArray)prop.Value, serializer);
}
}
// If the JSON is not what we expect, just return an empty list.
// (Could return null or throw an exception here instead if desired.)
return new List<T>();
}
private List<T> CreateListFromJArray(JArray array, JsonSerializer serializer)
{
List<T> list = new List<T>();
serializer.Populate(array.CreateReader(), list);
return list;
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then just add the converter to your Roles property and you should be good to go:
[JsonProperty("roles")]
[JsonConverter(typeof(ArrayOrWrappedArrayConverter<Role>))]
public List<Role> Roles { get; set; }
Working demo: https://dotnetfiddle.net/F6qgQB
the easiest way (not necessarily the cleanest) would be to manually alter the string before deserialising -
jsonString = jsonString.replace("\"roles\": {", "\"rolesContainer\": {");
jsonString = jsonString.replace("\"roles\":{", "\"rolesContainer\": {");
and then in your main code you would have both rolesContainer and roles as fields - and then merge them after
public List<Role> roles { get; set; }
public RoleContainer rolesContainer { get; set; }
public class RoleContainer {
Public List<Role> roles;
}
it's dirty, but it should work

How can I choose what type to deserialize at runtime based on the structure of the json?

I have some data stored as Json. One property in the data is either an integer (legacy data) like so:
"Difficulty": 2,
Or a complete object (new versions):
"Difficulty": {
"$id": "625",
"CombatModifier": 2,
"Name": "Normal",
"StartingFunds": {
"$id": "626",
"Value": 2000.0
},
"Dwarves": [
"Miner",
"Miner",
"Miner",
"Crafter"
]
},
I am trying to write a custom converter for the type that allows deserialization of both versions.
This is C#, using the latest version of newtonsoft.json.
I've written a converter, and deserializing the integer format is trivial - it's only the mix that is causing me trouble. The only way I can think to check is to try and fail; but this appears to leave the reader in an unrecoverable state. Also, calling deserialize in the catch block leads to an infinite loop.
public class DifficultyConverter : 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)
{
try
{
var jObject = serializer.Deserialize<JValue>(reader);
if (jObject.Value is Int32 intv)
return Library.EnumerateDifficulties().FirstOrDefault(d => d.CombatModifier == intv);
else
return null;
}
catch (Exception e)
{
return serializer.Deserialize<Difficulty>(reader);
}
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Difficulty);
}
}
Ideally I would be able to serialize into the new format always, and still support reading both formats. A couple of other options include:
Creating another serializer object that does not include the custom converter and calling it from the catch block.
Detecting out of date files at load and modifying the text before attempting to deserialize.
Kind of want to avoid those tho.
You have a couple of problems here:
You are getting an infinite recursion in calls to ReadJson() because your converter is registered with the serializer you are using to do the nested deserialization, either through settings or by directly applying [JsonConverter(typeof(DifficultyConverter))] to Difficulty.
The standard solution to avoid this is to manually allocate your Difficulty and then use serializer.Populate() to deserialize its members (e.g. as shown in this answer to Json.NET custom serialization with JsonConverter - how to get the "default" behavior) -- but you are also using PreserveReferencesHandling.Objects, which does not work with this approach.
What does work with reference preservation is to adopt the approach from this answer to JSON.Net throws StackOverflowException when using [JsonConvert()] and deserialize to some DTO that contains a property of type Difficulty which has a superseding converter applied directly to the property.
serializer.Deserialize<JValue>(reader); may advance the reader past the current token. This will cause the later attempt to deserialize as an object to fail.
Instead, just check the JsonReader.TokenType or preload into a JToken and check the Type.
Putting the above together, your converter should look like the following:
public class DifficultyConverter : 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 token = JToken.Load(reader);
switch (token.Type)
{
case JTokenType.Null:
return null;
case JTokenType.Integer:
{
var intv = (int)token;
return Library.EnumerateDifficulties().FirstOrDefault(d => d.CombatModifier == intv);
}
case JTokenType.Object:
return token.DefaultToObject(objectType, serializer);
default:
throw new JsonSerializationException(string.Format("Unknown token {0}", token.Type));
}
}
public override bool CanWrite => false;
public override bool CanConvert(Type objectType) => objectType == typeof(Difficulty);
}
Using the following extension methods:
public static partial class JsonExtensions
{
public static object DefaultToObject(this JToken token, Type type, JsonSerializer serializer = null)
{
var oldParent = token.Parent;
var dtoToken = new JObject(new JProperty(nameof(DefaultSerializationDTO<object>.Value), token));
var dtoType = typeof(DefaultSerializationDTO<>).MakeGenericType(type);
var dto = (IHasValue)(serializer ?? JsonSerializer.CreateDefault()).Deserialize(dtoToken.CreateReader(), dtoType);
if (oldParent == null)
token.RemoveFromLowestPossibleParent();
return dto == null ? null : dto.GetValue();
}
public static JToken RemoveFromLowestPossibleParent(this JToken node)
{
if (node == null)
return null;
// If the parent is a JProperty, remove that instead of the token itself.
var contained = node.Parent is JProperty ? node.Parent : node;
contained.Remove();
// Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
if (contained is JProperty)
((JProperty)node.Parent).Value = null;
return node;
}
interface IHasValue
{
object GetValue();
}
[JsonObject(NamingStrategyType = typeof(Newtonsoft.Json.Serialization.DefaultNamingStrategy), IsReference = false)]
class DefaultSerializationDTO<T> : IHasValue
{
public DefaultSerializationDTO(T value) { this.Value = value; }
public DefaultSerializationDTO() { }
[JsonConverter(typeof(NoConverter)), JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)]
public T Value { get; set; }
public object GetValue() => Value;
}
}
public class NoConverter : JsonConverter
{
// NoConverter taken from this answer https://stackoverflow.com/a/39739105/3744182
// To https://stackoverflow.com/questions/39738714/selectively-use-default-json-converter
// By https://stackoverflow.com/users/3744182/dbc
public override bool CanConvert(Type objectType) { throw new NotImplementedException(); /* This converter should only be applied via attributes */ }
public override bool CanRead { get { return false; } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); }
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); }
}
Demo fiddle here.

Edit Json property then deserialize with json.net [duplicate]

Assuming a json string like the following:
string json = '{"string_property":"foo_bar", ... other objects here ...}';
I was wondering if there's a way to run a transformation on the parsed object so that instead of getting foo_bar, I'll get foo bar after running the following method (can be anything really)
public string Transform(string s) {
return s.Replace("_"," ");
}
I can manually alter my poco after deserializing, but wondered what would be a "cleaner" approach?
You can transform your string properties as you deserialize your root object by using a custom JsonConverter targeted at all string type values:
public class ReplacingStringConverter : JsonConverter
{
readonly string oldValue;
readonly string newValue;
public ReplacingStringConverter(string oldValue, string newValue)
{
if (string.IsNullOrEmpty(oldValue))
throw new ArgumentException("string.IsNullOrEmpty(oldValue)");
if (newValue == null)
throw new ArgumentNullException("newValue");
this.oldValue = oldValue;
this.newValue = newValue;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var s = (string)JToken.Load(reader);
return s.Replace(oldValue, newValue);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then use it like:
var settings = new JsonSerializerSettings { Converters = new[] { new ReplacingStringConverter("_", "") } };
var result = JsonConvert.DeserializeObject<RootObject>(json, settings);
Note however that if individual string-type properties have their own converters applied directly with [JsonConverter(Type)], those converters will be used in preference to the ReplacingStringConverter in the Converters list.
I've ended up doing the following:
First, create a converter that only reads and all it does is url decode the string.
public class UrlDecoderConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var s = (string)JToken.Load(reader);
return HttpUtility.UrlDecode(s);
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, simply add the following to the POCO properties that need to be decoded:
[JsonConverter(typeof(UrlDecoderConverter))]
public string url { get; set; }

Json.Net Is converting on its own before using my JsonConverter

In my WPF code, I'm using Newtonsoft.Json to deserialize json into my models. First, I receive a Json string ('json') which I then parse into 'message'. (The object I want to deserialize is wrapped in a "data" field in the json string).
Activity message = JObject.Parse(json)["data"].ToObject<Activity>();
My Activity class uses several [JsonProperty] attributes to generate its fields. One of them is an enum called 'ActivityType'.
[JsonProperty("type")]
[JsonConverter(typeof(ActivityTypeConverter))]
public ActivityType Type { get; set; }
public enum ActivityType {
EmailOpen,
LinkClick,
Salesforce,
Unsupported
};
public class ActivityTypeConverter : JsonConverter {
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var rawString = existingValue.ToString().ToLower();
if (rawString.Contains("click"))
return ActivityType.LinkClick;
else if (rawString.Contains("salesforce"))
return ActivityType.Salesforce;
else if (rawString.Contains("email_open"))
return ActivityType.EmailOpen;
else
{
Console.WriteLine("unsupported " + rawString);
return ActivityType.Unsupported;
}
}
public override bool CanConvert(Type objectType)
{
return !objectType.Equals(typeof(ActivityType));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
What's bizarre and frustrating is that json objects which I know have "type":"email_open" are being deserialized as ActivityType.Unsupported, even though my converter should be deserializing them as EmailOpen.
Debugging has shown what the problem is:
the json field "type" is automatically deserializing "email_open" as EmailOpen and then it is sent through my converter. (It breaks then because my conditional checks for an underscore, while EmailOpen.ToString() doesn't have one.)
So my question then is: Why is it converting without my converter and how do I stop it? I just want it to only use my converter
I think your converter is being called -- it's just not working. The problem is that, rather than reading the new value from the JsonReader reader, you are using the value from the existingValue. But this second value is the pre-existing property value in the class being deserialized, not the value being read.
You need to load the value from the reader along the lines of Json.NET's StringEnumConverter. Here's a version that does that and also handles standard values of your enum by subclassing StringEnumConverter and passing the value read from the file to the base class for further processing:
public class ActivityTypeConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);
Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
if (reader.TokenType == JsonToken.Null)
{
if (!isNullable)
throw new JsonSerializationException();
return null;
}
var token = JToken.Load(reader);
if (token.Type == JTokenType.String)
{
var rawString = ((string)token).ToLower();
if (rawString.Contains("click"))
return ActivityType.LinkClick;
else if (rawString.Contains("salesforce"))
return ActivityType.Salesforce;
else if (rawString.Contains("email_open"))
return ActivityType.EmailOpen;
}
using (var subReader = token.CreateReader())
{
while (subReader.TokenType == JsonToken.None)
subReader.Read();
try
{
return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
}
catch (Exception ex)
{
return ActivityType.Unsupported;
}
}
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ActivityType);
}
}

Change default null value in JSON.NET

Is there some way to set what the default representation for null values should be in Json.NET?
More specifically null values inside an array.
Given the class
public class Test
{
public object[] data = new object[3] { 1, null, "a" };
}
Then doing this
Test t = new Test();
string json = JsonConvert.SerializeObject(t);
Gives
{"data":[1,null,"a"]}
Is it possible to make it look like this?
{"data":[1,,"a"]}
Without using string.Replace.
Figured it out. I had to implement a custom JsonConverter.
As others mentioned this will not produce valid/standard Json.
public class ObjectCollectionConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(object[]);
}
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)
{
object[] collection = (object[])value;
writer.WriteStartArray();
foreach (var item in collection)
{
if (item == null)
{
writer.WriteRawValue(""); // This procudes "nothing"
}
else
{
writer.WriteValue(item);
}
}
writer.WriteEndArray();
}
}
Use it like this
Test t = new Test();
string json = JsonConvert.SerializeObject(t, new ObjectCollectionConverter());

Categories