gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:37:01 24 4
gpt4 key购买 nike

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

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中描述了相同的问题,但我正在寻找一种优雅,简单的解决方案,但未提出该解决方案。

最佳答案

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

关于json - 使用C#中的嵌套字符串表示json数据的反序列化模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45435911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com