从昨天开始,我尝试在我的 C#-Project 中通过 Xabe-Wrapper 实现 ffmpeg。
我使用 FFMpeg => FFProbe 从某些电影中获取格式和流数据作为 json 字符串。这是我为 Streams 获得的 json。
"{
"streams": [
{"codec_name": "mpeg4", "codec_type": "video"},
{"codec_name": "mp3" , "codec_type": "audio"}
]
}"
关注Newtonsoft Wiki ,我将其反序列化为 DataSet。我开始四处玩耍,并找到了一种在“oneliner”中执行此操作的方法。
Streams = (JsonConvert.DeserializeObject<DataSet>(StreamProbeJSON,
JSerializerSettings)).Tables["streams"].AsEnumerable().Select(value => new
FormatAVInfo.SInfo(value.Field<string>("codec_type"), value.Field<string>
("codec_name")));
对于格式,我得到这个 Json
{
"format": {
"format_name": "avi",
"probe_score": 100
}
}
关注Newtonsoft Wiki ,我将这个反序列化为字典,但我无法再次在 oneliner 中执行此操作。这不是一个大问题,但我想现在我怎么能做到这一点?
我试过这个
Format = (JsonConvert.DeserializeObject<Dictionary<string,
Dictionary<string, string>>>(FormatProbeJSON, JSerializerSettings))
["format"].Select(value => new FormatAVInfo.FInfo(value["format_name"],
value["probe_score"]));
但是,可以肯定的是,我得到了一个 KeyValuePair 并且无法为此使用索引器。我也尝试过使用 JObject,结果相同。当然,我可以制作另一个字段
Dictionary<string,string> Temp =
(JsonConvert.DeserializeObject<Dictionary<string,
Dictionary<string, string>>>(FormatProbeJSON, JSerializerSettings))
["format"]
然后实例化,但我很好奇是否有办法做到这一点。
谢谢
最佳答案
您应该将此类数据反序列化为模型,而不是 Dictionary
,因为它似乎有一个固定的结构——而不是一个动态的结构。
例如,我们将模型称为“MyMovieData”。
public class MyMovieData
{
[JsonProperty("streams"]
public MovieStream[] Streams { get; set; }
}
public class MovieStream[]
{
[JsonProperty("codec_name")]
public string CodecName { get; set; }
[JsonProperty("codec_type")]
public string CodecType { get; set; }
}
现在你可以用一种非常简单的方式反序列化它:
MyMovieData bigBuckBunnyData = JsonConvert.DeserializeObject<MyMovieData>(json);
MovieStream[] bigBuckBunnyStreams = bigBuckBunnyData.Streams;
关于c# - 如何使用 Lambda/LINQ 从字典中启动一个类对象,由 Newtonsoft.Json 解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213072/