【发布时间】:2022-01-12 01:59:50
【问题描述】:
我正在从 API 读取一个 json 字符串(在 SSIS 的脚本组件中)。 json 看起来像下面的那个(这只是一个记录,真正的字符串包含更多)。当尝试反序列化为包含所需属性的类时,我想将“costCenters”属性的“值”放入表中的字符串属性中。然而,由于 costCenters-value 本身包含一个 JSON,因此反序列化失败(因为它遇到了其中的对象)。
如果我从我的类中排除属性 CostCenters,它可以很好地反序列化其他属性。我认为(希望)可以将内部 JSON 强制转换为字符串属性?有什么建议吗?
这是我用于反序列化的类:
internal class Unit
{
public int ParentId { get; set; }
public int CompanyId { get; set; }
public string Abbreviation { get; set; }
public string AbbreviationPath { get; set; }
public int Manager { get; set; }
public int UnitId { get; set; }
public string Name { get; set; }
public string LevelDescription { get; set; }
public int OrfuCompanyId { get; set; }
public string Resh { get; set; }
//If the below propery is commented out, the deserializing works fine.
public string CostCenters { get; set; }
public int Level { get; set; }
public int OrfuUnitId { get; set; }
}
这就是我为 NewtonSoft 调用反序列化器的方式:
var units = new List<Unit>();
units = JsonConvert.DeserializeObject<List<Unit>>(jsonString);
这是 jsonString 的外观(已编辑):
[
{
"$id": "1",
"parentId": 999,
"companyId": 9123,
"abbreviation": "ZZZ",
"abbreviationPath": "SOMEPATH",
"costCenters": [
{
"$id": "12",
"costCenter": "12345",
"costCenterSourceId": "99",
"costCenterSource": "TBF",
"costCenterTypeId": "999",
"costCenterType": "TypeOfCostCenter",
"startDate": "2018-01-01T00:00:00",
"endDate": "9999-12-31T00:00:00"
},
{
"$id": "88",
"costCenter": "191945444",
"costCenterSourceId": "88",
"costCenterSource": "TBB",
"costCenterTypeId": "15",
"costCenterType": "SomeTextHere",
"startDate": null,
"endDate": null
}
],
"manager": 12345678,
"deputy": 0,
"homeShare": "\\\\someaddress.net\\someFolder\\SomeCode",
"objectGuid": "ThisIsAGUID",
"distinguishedName": "OU=ABC,OU=NNN,OU=FFF,OU=HHH,OU=HNV,OU=IDK,DC=heipaadeg,DC=com",
"orfuUnitId": 9125,
"orfuCompanyId": 9123,
"resh": "123456789",
"nis": "",
"unitId": 4321,
"name": "2 some name",
"level": 9,
"levelDescription": "Level number 4"
}
]
【问题讨论】:
-
为什么需要 CostCenters 作为字符串,而不是数组?
-
我不确定我是否理解您的问题。您是说要将 JSON 数组中的
CostCenters反序列化为原始 JSON 字符串,然后将其重新序列化为嵌入的 JSON 字符串文字?如果是这样,您可以使用自定义JsonConverter来做到这一点。 Efficiently get full json string in JsonConverter.ReadJson() 和你的问题是否充分? -
@Serge 抱歉回复晚了,我昨天不得不注销。我需要它作为字符串的原因是我即将替换第三方组件 i SSIS,它将整个记录转储到 SQL 表中,并且整个 CostCenters 字符串转储到 varchar(max) 列中。谢谢大家的建议,我会审查它们,看看其中一些是否对我有用。