我有一个包含的json文件
{
"Accounts": null,
"AccountTypes": null,
"Actions": null,
"Photos": [
{
"Instance": "...",
"Key": "..."
},
....
]
}
现在我想从照片对象中获取所有的实例属性。我有以下代码:
var photos = new List<Photo>();
string json = File.ReadAllText(file);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(object));
var jsonPhotos = jsonObj.Photos as IEnumerable<dynamic>;
var instances = jsonPhotos.Select(x => x.Instance);
foreach (var instance in instances)
photos.Add(new Photo
{
Document = Convert.FromBase64String(instance)
});
但是,jsonPhotos.Select(x=>x.Instance(;没有返回任何内容。。。
我可以通过使用使事情正常工作
var instances = new List<string>();
foreach (var photo in jsonPhotos)
instances.Add(photo.Instance.Value);
但是我能用LINQ的方法解决这个问题吗?
为什么不使用Json.Linq
?将JSON解析为JObject
实例,然后将Photos
数组中的每个令牌映射到Photo
实例(我省略了Convert.FromBase64String
,因为OP样本没有有效的base64数据,但可以很容易地添加转换Instance
值(
var json = JObject.Parse(jsonString);
var photos = json["Photos"]
.Select(token => new Photo
{
Document = token["Instance"]?.Value<string>()
})
.ToList();
.Select(x => x.Instance)
确实在.NET Core 3.1上返回了...
。您能验证json
变量的内容实际上是您所期望的吗?
特别是
jsonPhotos.Select(x => x.Instance);
正常工作,而
jsonPhotos.Select(x => x.SomeNonExistingProperty);
不枚举任何值/空值。
例如,此代码打印Instance A
,然后打印Instance B
,然后不打印两次:
var json = @"
{
""Photos"": [
{
""Instance"": ""Instance A"",
""Key"": ""...""
},
{
""Instance"": ""Instance B"",
""Key"": ""...""
}]
}";
var jsonObj = JsonConvert.DeserializeObject<dynamic>(json);
var jsonPhotos = jsonObj.Photos as IEnumerable<dynamic>;
var instances = jsonPhotos.Select(x => x.Instance);
foreach (var instance in instances)
{
Console.WriteLine(instance);
}
// In contrast, this one will print empty lines.
instances = jsonPhotos.Select(x => x.SomeNonExistingProperty);
foreach (string instance in instances)
{
Console.WriteLine(instance);
}
我可以直接将反序列化更改为dynamic
,但它也适用于问题中的原始代码。