Deserialize model with nested string represented json data in C#
class Nested{ public string Name {get; set;} public int Id {get; set;}}class Model{ [JsonProperty] public string N { get { return JsonConverter.DeserializeObject<Nested>(Nested); } set{ Nested = JsonConverter.SerializeObject(value); } } // Use this in your code [JsonIgnore] public Nested Nested {get;set;} public string Name {get; set;} public int Id {get; set;}}
I had similar issues but in the opposite direction (due to the EF proxies and that stuff, a long history)
But I'd say that this could be a good hint for you, I did this in my startup, on ConfigureServices method:
// Add framework services.services.AddMvc().AddJsonOptions(options => { // In order to avoid infinite loops when using Include<>() in repository queries options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; });
I hope it helps you to solve your issue.
Juan
you can serialize it yourself with your own code, using Runtime.Serialization
something like this
[Serializable]class Model{ [JsonProperty] public Nested N {get; set;} public string Name {get; set;} public int Id {get; set;} protected Model(SerializationInfo info, StreamingContext context) { Name = info.GetString("Name"); Id = info.GetInt32("Id"); try { child = (Model)info.GetValue("N", typeof(Model)); } catch (System.Runtime.Serialization.SerializationException ex) { // value N not found } catch (ArgumentNullException ex) { // shouldn't reach here, type or name is null } catch (InvalidCastException ex) { // the value N doesn't match object type in this case (Model) } }}
once you use Model class as your parameter it will automatically use this serializer we just did.