Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize model with nested string represented json data in C#

I have a model which looks like that:

class Nested{
  public string Name {get; set;}
  public int Id {get; set;}
}

class Model{
  [JsonProperty]
  public Nested N {get; set;}
  public string Name {get; set;}
  public int Id {get; set;}
}

and a markup for that is something like this:

<input asp-for="Name">
<input asp-for="id">
<input type="hidden" name="n" value="@JsonConvert.SerializeObject(new Nested())">

However when I posting this form back it fails on deserialization because N field looks like encoded twice. So this code works:

var b = JsonConvert.DeserializeAnonymousType(model1, new { N = ""}); 
var c = JsonConvert.DeserializeObject<Nested>(b.N);

but this one fails:

var d = JsonConvert.DeserializeAnonymousType(model1, new {N = new Nested()});

What i need is to make it work with JsonConvert.DeserializeObject<Model>(model1). What should I change to make it work?


example:

{"name":"Abc","id":1,"n":"{\"id\":2,\"name\":\"BBB\"}"}

The same problem described in this question but I'm looking for an elegant, simple solution, which wasn't proposed.

like image 475
Natasha Avatar asked Aug 01 '17 10:08

Natasha


1 Answers

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;}
}
like image 113
Akash Kava Avatar answered Nov 09 '22 10:11

Akash Kava