I having some trouble while trying to deserialize some json, because it's comming with unnescaped double quotes from ther server. As I don't have access to fix this on the server side I'm trying to ignore problematic json. To do so, I've followed these answers https://stackoverflow.com/a/21542099/2779990 and Ignore parsing errors during JSON.NET data parsing. When I use errorArgs.ErrorContext.Handled = true;
the response object is null
.
So I implement my own converter:
public class FieldConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(FieldOperationDomain);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
FieldDomain field = new FieldDomain();
try
{
JObject jObject = JObject.Load(reader);
JToken name = jObject["Name"];
if (name.Type == JTokenType.String)
{
field.Name = (string)name;
}
else
{
field.Name = null;
}
JToken value = jObject["Value"];
if (value.Type == JTokenType.String)
{
field.Value = (string)value;
}
else
{
field.Value = null;
}
return field;
} catch (Exception e)
{
return new FieldDomain
{
Name = "",
Value = ""
};
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
My json looks like this:
[
{
"id": "1d5c9ea3-7eb3-4fff-b8da-0a4dec891054",
"RecordType": 1,
"Field": []
},
{
"id": "1d5c9ea3-7eb3-4fff-b8da-0a4dec891054",
"RecordType": 1,
"Field": [
{
"Name": "something",
"Value": "Other something"
},
{
"Name": "something",
"Value": "Problematic "Other something""
}
]
}
]
My domain objects look's like this:
public class MainDomain
{
[JsonProperty("id")]
public long RecordType { get; set; }
[JsonProperty("RecordType")]
public long RecordType { get; set; }
[JsonProperty("Fields")]
public IEnumerable<Field> Fields { get; set; }
}
[JsonConverter(typeof(FieldOperationConverter))]
public class FieldDomain
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Value")]
public string Value { get; set; }
[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
{
errorContext.Handled = true;
}
}
I even also try to add this to the problematic object:
[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
{
errorContext.Handled = true;
}
The problem is that even using the try catch block to catch any exception on JObject jObject = JObject.Load(reader);
, this not prevent JsonConvert.DeserializeObject<IEnumerable<T>>(document, settings);
from throwing an exception. It's possible to do something similar to errorArgs.ErrorContext.Handled = true;
inside ReadJson
method?