无效的JSON原语-自定义序列化/反序列化
本文关键字:序列化 反序列化 自定义 JSON 原语 无效 | 更新日期: 2023-09-27 18:17:13
我有一个JSON文件,从web服务返回..
facilityName: Ragley DRI01{
"DataCenterManager": {
"first": "",
"second": "Cory Kemp"
},
"RegionalDataCenterManager": {
"first": "",
"second": "John Farrell"
},
"LastUpdatedBy": {
"first": "DCInfoSyncRole",
"second": "v-asalam"
},
"Client": {
"first": "DCInfoSyncRole",
"second": "FacilityMasterPortal"
}
}
facilityName: Quitman, MEI01{
"DataCenterManager": {
"first": "",
"second": "Cory Kemp"
},
"RegionalDataCenterManager": {
"first": "",
"second": "John Farrell"
},
"LastUpdatedBy": {
"first": "DCInfoSyncRole",
"second": "v-asalam"
},
"Client": {
"first": "DCInfoSyncRole",
"second": "FacilityMasterPortal"
}
}
我知道这是无效的根据JSONLint,但我必须反序列化这个JSON对象结构化数据表。
我需要自定义序列化/反序列化吗?
不使用JSON.net的任何帮助是最感激的。
恐怕您面临的可怕格式与真正的JSON相差甚远,以至于JSON解析器无法调整以解析它。您能做的最好的事情是手动将其转换为有效的JSON,然后像往常一样进行解析。
当然,这将是容易出错和脆弱的,但如果你真的需要这样做,这是可能的。像这样的东西可以作为开始
var resultBuilder = new StringBuilder();
resultBuilder.Append("[");
var facilityNameRegex = new Regex("facilityName: ((.)+(?={))");
var facilities = facilityNameRegex.Matches(text);
var lastIndex = facilities.Count - 1;
for (int i = 0; i <= lastIndex; i++)
{
var facilityName = facilities[i].Groups[1].Value;
var bodyStartIndex = facilities[i].Index + facilities[i].Length;
var body = (i < lastIndex) ?
text.Substring(bodyStartIndex, facilities[i + 1].Index - bodyStartIndex)
: text.Substring(bodyStartIndex);
resultBuilder.AppendFormat("{{'"facilityName'": {0}, '"settings'": {1}}}",
HttpUtility.JavaScriptStringEncode(facilityName, addDoubleQuotes: true),
body);
if (i != lastIndex)
{
resultBuilder.Append(",");
}
}
resultBuilder.Append("]");
Console.WriteLine(resultBuilder.ToString()); // result is a valid JSON array