CSharp · Console
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using System.Collections.Generic;
namespace MyNamespace
{
public class ConvolutedObject
{
public string A = "";
public int B = 0;
}
public class MySerializationBinder : DefaultSerializationBinder
{
private string _context;
public MySerializationBinder(string context)
{
_context = context;
}
public override Type BindToType(string assemblyName, string typeName)
{
// Some more subtitutions. I won't bore you with that.
switch (typeName.ToLower())
{
case "bool":
return typeof(bool);
case "int":
case "int32":
return typeof(Int32);
default: return base.BindToType(assemblyName, typeName);
}
}
}
public class MyCustomConverter : JsonConverter
{
protected string ObjectFileConverter(string objectFile)
{
// This part does some text substitutions as the "serialized object" is not a perfect match
// ......
return objectFile;
}
public override bool CanConvert(Type objectType)
{
return typeof(ConvolutedObject).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
static List<string> errors = new List<string>();
static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
Error = delegate (object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
//Converters = ??,
TypeNameHandling = TypeNameHandling.All,
ObjectCreationHandling = ObjectCreationHandling.Replace,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
SerializationBinder = new MySerializationBinder("Context")
};
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
string adaptedObject = token.ToString();
// Do some text substitution to obtain the correct object format so that it can get deserialized
adaptedObject = ObjectFileConverter(adaptedObject);
return JsonConvert.DeserializeObject<ConvolutedObject>(adaptedObject, _jsonSettings);
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
public class Program
{
public static void Main()
{
var MyConvolutedObject=
JsonConvert.DeserializeObject<MyNamespace.ConvolutedObject>(
GetJson(), new MyNamespace.MyCustomConverter());
}
public static string GetJson()
{
string json = @"[
{""A"": ""150000001"",
""B"": ""Json1""}]";
return json;
}
}