使用嵌套字符串反序列化模型表示C#中的json数据

时间:2017-08-01 10:56:44

标签: json asp.net-mvc serialization asp.net-core asp.net-core-mvc

我有一个看起来像这样的模型:

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;}
}

并且标记就是这样的:

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

然而,当我发布此表单时,它在反序列化时失败,因为N字段看起来像编码两次。所以这段代码有效:

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

但是这个失败了:

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

我需要的是让它与JsonConvert.DeserializeObject<Model>(model1)一起使用。我应该改变什么才能使它发挥作用?

示例:

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

this question中描述了同样的问题,但我正在寻找一种优雅,简单的解决方案,但尚未提出。

4 个答案:

答案 0 :(得分:2)

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;}
}

答案 1 :(得分:0)

我有类似的问题,但反方向(由于EF代理和那些东西,历史悠久)

但是我要说这对你来说是一个很好的提示,我在我的启动中使用ConfigureServices方法做了这个:

// 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;
         }); 

我希望它可以帮助您解决问题。

答案 2 :(得分:0)

您可以使用Runtime.Serialization

使用自己的代码自己serialize

类似这样的事情

[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)
        }
        }
}

一旦你使用Model类作为参数,它将自动使用我们刚刚做的这个序列化器。

答案 3 :(得分:-1)

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