我在解决序列化问题。
我在SQL表中有一列,其中包含一个pascal大小写的JSON片段:
{
"HistoryOpertions": [
{
"OperationTitle": "Titre Op",
"OperationDetails": "Details Op"
},
{
"OperationTitle": "2",
"OperationDetails": "Op 2"
},
{
"OperationTitle": "by Ol",
"OperationDetails": "Test",
"OperateurName": "Olivier Matrot",
"TimeStamp": 637100138608377997
}
],
"TimestampLastModification": "2019-11-29T11:09:16.1621275Z",
"AlertInstructions": [
{
"InstructionId": 1,
"OperateurName": null,
"CheckPoint": false,
"TimeStamp": null
}
],
"AlertTitle": "Alerte safe protect",
"LiftingDoubtId": 2,
"SupportId": 3
}
我有以下代码来解析此片段,进行一些修改,然后创建一个新对象并将其序列化回字符串。这次我希望属性名称采用驼峰式:
var json = JObject.Parse(existingAlertDetailEntity.SafeProtectCustomInfo ?? "{}");
JArray alertInstructions = json["AlertInstructions"] as JArray;
foreach (var instruction in alertInstructions)
{
if (instruction[nameof(AlertInstruction.InstructionId)].ToObject<int>() == model.InstructionId)
{
bUpdated = true;
instruction[nameof(AlertInstruction.TimeStamp)] = model.Status ? DateTime.UtcNow.Ticks : (long?)null;
instruction[nameof(AlertInstruction.OperateurName)] = model.Status ? user.DisplayName : null;
instruction[nameof(AlertInstruction.CheckPoint)] = model.Status;
break;
}
}
var jsonSerializer = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore,ContractResolver = new CamelCasePropertyNamesContractResolver() };
string jsonToBeReturned = JsonConvert.SerializeObject(
new {
model.AlertId,
AlertInstructions = JArray.FromObject(
json["AlertInstructions"],
JsonSerializer.Create(new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
})),
}, jsonSerializer);
结果如下:
{
"alertId":1295041,
"alertInstructions":[
{
"InstructionId":1,
"TimeStamp":637111473877506411,
"OperateurName":"Olivier Matrot",
"CheckPoint":true
},
{
"InstructionId":2,
"TimeStamp":637112167087671938,
"OperateurName":"Olivier Matrot",
"CheckPoint":true
}
]
}
我们可以看到alertInstructions数组仍然包含Pascal Cased属性名称。
您可以使用来反序列化JSON ExpandoObject
,对其进行修改并将其序列化为字符串。
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore,ContractResolver = new CamelCasePropertyNamesContractResolver() };
dynamic json = JsonConvert.DeserializeObject<ExpandoObject>(JSON);
// modify your structure here...
json.AlertInstructions[0].TimeStamp = 1234;
var jsonToBeReturned = JsonConvert.SerializeObject(new {
AlertId = 42,
AlertInstructions = json.AlertInstructions
}, Formatting.Indented, settings);
有关示例,另请参见小提琴。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句