[英]Deserialize JSON to a dynamic object or a class in C#
I am trying to deserialize JSON into an object so I can add it to elastic search.我正在尝试将 JSON 反序列化为 object 以便我可以将其添加到弹性搜索中。 JSON can be of many different object types in the project so I would like the function to be dynamic. JSON 在项目中可以是许多不同的 object 类型,所以我希望 function 是动态的。
First I am serializing the Data that I get from EF Core context首先,我正在序列化从 EF Core 上下文中获得的数据
var serializedObject = JsonConvert.SerializeObject(document, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
Next I would like to deserialize to an object.接下来我想反序列化为 object。 For example if I have例如,如果我有
public class EValues
{
public dynamic values { get; set; }
}
var test = JsonConvert.DeserializeObject<EValues>(serializedObject.ToString());
I would like the JSON to be deserialized to the below:我希望将 JSON 反序列化为以下内容:
{
"values":{
"StudentId":"60712555-ff1d-4a3e-8c81-08d9c2fc4423",
"Student":{
"Name":"string",
"Country":"string",
"Street":"string"
}
}
}
The serializedObject
JSON I am actually trying to deserialize: serializedObject
JSON 我实际上是在尝试反序列化:
{
"StudentId":"60712555-ff1d-4a3e-8c81-08d9c2fc4423",
"Student":{
"Name":"string",
"Country":"string",
"Street":"string"
}
}
You can just do:你可以这样做:
var test = new EValues {
values = JsonConvert.DeserializeObject<dynamic>(serializedObject)
};
The JSON that would correspond to EValues
would have an extra level of nesting { "values": {} }
not present in your serializedObject
JSON.对应于 EValues 的EValues
将具有额外的嵌套级别{ "values": {} }
不存在于您的serializedObject
JSON 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.