【发布时间】:2021-09-29 10:32:06
【问题描述】:
我有这样的json
{
"guid": "b1e3c29f-066f-417b-b6b6-795ffae90f0a",
"status": "complete",
"type": "colors",
"results": {
"events": [
{
"title": "event1",
"other": {
"Red": "red",
"Green": "green",
"Blue": "blue"
}
},
{
"title": "event2",
"other": {
"Yelow": "yellow",
"Orange": "orange"
}
}
]
}
}
反序列化的类看起来像这样
public class Other
{
public string Red { get; set; }
public string Green { get; set; }
public string Blue { get; set; }
public string Yelow { get; set; }
public string Orange { get; set; }
}
public class Event
{
public string title { get; set; }
public Other other { get; set; }
}
public class Results
{
public List<Event> events { get; set; }
}
public class Root
{
public string guid { get; set; }
public string status { get; set; }
public string type { get; set; }
public Results results { get; set; }
}
当我反序列化这个 json 时
var root = JsonConvert.DeserializeObject<Root>(JsonContent);
一切正常。
问题是json部分"Other"的内容是可变的,我不知道它的完整内容。
我还需要将这些类放入数据库中。
有没有办法将 json 部分 "Other" 反序列化为一个带有原始文本的字符串字段,并看起来像这样:
public class Other
{
public string AllFieldsFromOtherSectionAsRawText { get; set; }
}
【问题讨论】:
-
你在使用 Newtonsoft Json.NET,对吗?
-
您可以将
Other的类型更改为JObject,此时它只是“一些任意的JSON 对象” -
是的,Newtonsoft Json.NET。
-
谢谢@JonSkeet,你拯救了我的一天! :) 你的想法最适合我的场景! :)