嵌套字符串反序列化模型表示在C#中的JSON数据
我有一个模型,它看起来像这样:嵌套字符串反序列化模型表示在C#中的JSON数据
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;}
}
这是一个很好的方式来使这个工作的确切场景,但事实上,这样的代码将需要在每个模型具有类似的结构看起来相当失望。 –
@silent_coder对于一次性使用,这一个是最简单的,否则你当然可以编写一些接口和JsonDeserializer,并注册它,所有工作都是一次性使用太多。 –
尝试
var d = JsonConvert.DeserializeAnonymousType(model1, new {N = new Nested(),
Name = "", Id = 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;
});
我希望它可以帮助您解决问题。
胡安
,你可以用自己的代码自己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)
}
}
}
Runtime.Serialization
东西,一旦你使用模型类作为您的参数,它会自动使用该串行我们刚刚做到了。
没有示例JSON数据的JSON序列化问题? – niksofteng
那么,我添加了一个例子,但是基于类似问题和情况的链接,反序列化在一个案例中起作用,在其他案例中不起作用 - 很明显,json结构不是问题。那么,即使问题已经确定 - 解决唯一的问题。 – Natasha