【发布时间】:2021-06-01 09:02:44
【问题描述】:
考虑以下类:
public class ImageDataModel
{
public JsonObject CaptureResultData { get; }
public SmartphoneCommand SmartphoneCommand { get; }
public LightStageCommand LightStageCommand { get; }
public string TimeStamp { get; }
public ImageDataModel(string _captureResultData, LightStageCommand _lightStageCommand, SmartphoneCommand _smartphoneCommand)
{
CaptureResultData = JsonObject.Parse(_captureResultData);
SmartphoneCommand = _smartphoneCommand;
LightStageCommand = _lightStageCommand;
TimeStamp = DateTime.Now.ToString("HH:mm.ss, dd. MM. yyyy");
}
}
SmartphoneCommand和LightStageCommand是可序列化的对象,这些都没有问题。但是,在构造函数中,_captureResultData 已经是 JsonObject 类型的序列化 JSON 字符串。由于我希望此字符串中的数据显示为序列化对象数据,而不是 JSON 文件中的单个字符串,因此我将其设置为 JsonObject。
问题是,序列化后,CaptureResult 数据在 JSON 文件中显示如下:
"CaptureResultData": {
"android.control.afMode": {
"ValueType": 2
},
"android.colorCorrection.gains": {
"ValueType": 3
},
"android.control.awbMode": {
"ValueType": 2
},
"android.lens.focalLength": {
"ValueType": 2
},
"android.lens.focusDistance": {
"ValueType": 2
},
"android.control.aeMode": {
"ValueType": 2
},
"android.colorCorrection.mode": {
"ValueType": 2
},
"android.colorCorrection.transform": {
"ValueType": 3
},
"android.lens.aperture": {
"ValueType": 2
},
"android.sensor.sensitivity": {
"ValueType": 2
},
"android.sensor.exposureTime": {
"ValueType": 2
}
},
原始字符串包含正确的数据。如何强制序列化显示实际数据,而不是 ValueType?
为了完整起见,以下是序列化的完成方式:
using (StreamWriter jsonFile = File.CreateText(uniqueFilePaths[2]))
{
JsonSerializer serializer = new JsonSerializer
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
serializer.Serialize(jsonFile, new ImageDataModel(captureResultString, lightStageCommand, cameraCommand));
}
【问题讨论】:
-
我目前对该问题的解决方案是将属性设为字典:
CaptureResultData = JsonConvert.DeserializeObject<Dictionary<string, string>>(_captureResultData);。它有效,但我想这只是一个不必要的额外转换步骤,所以我不喜欢它。 -
您已标记此json.net,但
JsonObject是什么?它似乎不是该库的一部分。 -
@dbc 不,但 newtonsoft 是 json.net。
-
我知道 Newtonsoft 是 Json.NET。但是为了帮助您,我们需要知道
JsonObject是什么。是System.Json.JsonObject吗? -
哦,对不起 - 我误会了。我目前不在我的工作机器上,但由于我使用的是
Parse()函数,它应该是Windows.Data.Json.JsonObject