将LINQ-to-JSON查询从C#转换为VB.NET后,如何解决InvalidCastException? [英] How to resolve InvalidCastException after translating LINQ-to-JSON query from c# to VB.NET?
问题描述
我正在尝试使用此c#答案来自
I am trying to use code from this c# answer to Convert nested JSON to CSV but my project is VB.NET.
I tried few online converters but without much success. C# version works great but the VB.NET versions throw an InvalidCastException
. What might be the problem ?
我的JSON:
{
"Response": [
[
{
"id": 136662306,
"symbol": "aaa",
"status": "ACTIVE",
"base": "731.07686321",
"amount": "6.95345994",
"timestamp": "1524781083.0",
"swap": "0.0",
"pl": "5127.4352653395923394"
},
{
"id": 137733525,
"symbol": "bbb",
"status": "ACTIVE",
"base": "636.75093128",
"amount": "1.1",
"timestamp": "1531902193.0",
"swap": "0.0",
"pl": "687.800226608"
}
]
]
}
我的C#版本有效
JObject obj = JObject.Parse(json);
// Collect column titles: all property names whose values are of type JValue, distinct, in order of encountering them.
var values = obj.DescendantsAndSelf()
.OfType<JProperty>()
.Where(p => p.Value is JValue)
.GroupBy(p => p.Name)
.ToList();
var columns = values.Select(g => g.Key).ToArray();
// Filter JObjects that have child objects that have values.
var parentsWithChildren = values.SelectMany(g => g).SelectMany(v => v.AncestorsAndSelf().OfType<JObject>().Skip(1)).ToHashSet();
// Collect all data rows: for every object, go through the column titles and get the value of that property in the closest ancestor or self that has a value of that name.
var rows = obj
.DescendantsAndSelf()
.OfType<JObject>()
.Where(o => o.PropertyValues().OfType<JValue>().Any())
.Where(o => o == obj || !parentsWithChildren.Contains(o)) // Show a row for the root object + objects that have no children.
.Select(o => columns.Select(c => o.AncestorsAndSelf()
.OfType<JObject>()
.Select(parent => parent[c])
.Where(v => v is JValue)
.Select(v => (string)v)
.FirstOrDefault())
.Reverse() // Trim trailing nulls
.SkipWhile(s => s == null)
.Reverse());
// Convert to CSV
var csvRows = new[] { columns }.Concat(rows).Select(r => string.Join(",", r));
var csv = string.Join("\n", csvRows);
我的VB.NET版本具有以下异常:
My VB.NET version gives the following exception:
System.InvalidCastException:'无法转换类型为'WhereSelectEnumerableIterator`2'的对象
System.InvalidCastException: 'Unable to cast object of type 'WhereSelectEnumerableIterator`2
Dim obj As JObject = Nothing
obj = JObject.Parse(json)
Dim values = obj.DescendantsAndSelf().
OfType(Of JProperty)().
Where(Function(p) TypeOf p.Value Is JValue).
GroupBy(Function(p) p.Name).ToList()
Dim columns = values.[Select](Function(g) g.Key).ToArray()
Dim parentsWithChildren = values.SelectMany(Function(g) g).
SelectMany(Function(v) v.AncestorsAndSelf().
OfType(Of JObject)().Skip(1)).ToHashSet()
Dim rows = obj.DescendantsAndSelf().
OfType(Of JObject)().
Where(Function(o) o.PropertyValues().
OfType(Of JValue)().Any()).
Where(Function(o) o = obj OrElse Not parentsWithChildren.Contains(o)).
[Select](Function(o) columns.[Select](Function(c) o.AncestorsAndSelf().
OfType(Of JObject)().
[Select](Function(parent) parent(c)).
Where(Function(v) TypeOf v Is JValue).
[Select](Function(v) CStr(v)).
FirstOrDefault()).
Reverse().
SkipWhile(Function(s) s Is Nothing).
Reverse())
Dim csvRows = {columns}.Concat(rows).[Select](Function(r) String.Join(",", r)) ' HERE IS WHERE THE EXCEPTION OCCURS
Dim csv = String.Join(vbLf, csvRows)
例外
{"Unable to cast object of type 'WhereSelectEnumerableIterator`2[Newtonsoft.Json.Linq.JObject,System.Collections.Generic.IEnumerable`1[System.String]]' to type 'System.Collections.Generic.IEnumerable`1[System.String[]]'."}
推荐答案
为使{columns}.Concat(rows)
工作,看来您需要向 Enumerable.Concat(IEnumerable<TSource>, IEnumerable<TSource>)
是正确推断:
In order for {columns}.Concat(rows)
to work, it seems you need to add an explicit call to AsEnumerable()
in order to make sure the type TSource
for Enumerable.Concat(IEnumerable<TSource>, IEnumerable<TSource>)
is inferred correctly:
Dim csvRows = { columns.AsEnumerable() }.Concat(rows) _
.Select(Function(r) String.Join(",", r))
固定小提琴#1 此处.
DirectCast({columns}, IEnumerable(Of IEnumerable(Of String)))
似乎也可以正常工作,如评论所述: //stackoverflow.com/users/4934172/ahmed-abdelhameed>艾哈迈德·阿卜杜勒·哈密德:
A DirectCast({columns}, IEnumerable(Of IEnumerable(Of String)))
also seems to work, as mentioned in comments by Ahmed Abdelhameed:
Dim csvRows = DirectCast({columns}, IEnumerable(Of IEnumerable(Of String))).Concat(rows) _
.Select(Function(r) String.Join(",", r))
固定小提琴#2 此处.
在不使用推理的情况下显式调用Enumerable.Concat(Of IEnumerable(Of String))
也可以:
Calling Enumerable.Concat(Of IEnumerable(Of String))
explicitly, without making use of inferencing, works also:
Dim csvRows = Enumerable.Concat(Of IEnumerable(Of String))({columns}, rows) _
.Select(Function(r) String.Join(",", r))
固定的小提琴#3 此处.
因此,您的整个代码应如下所示:
Thus your entire code should look like:
Dim obj As JObject = JObject.Parse(json)
Dim values = obj.DescendantsAndSelf().OfType(Of JProperty)().Where(Function(p) TypeOf p.Value Is JValue).GroupBy(Function(p) p.Name).ToList()
Dim columns = values.[Select](Function(g) g.Key).ToArray()
Dim parentsWithChildren = values.SelectMany(Function(g) g).SelectMany(Function(v) v.AncestorsAndSelf().OfType(Of JObject)().Skip(1)).ToHashSet()
Dim rows = obj.DescendantsAndSelf() _
.OfType(Of JObject)() _
.Where(Function(o) o.PropertyValues().OfType(Of JValue)().Any()) _
.Where(Function(o) o.Equals(obj) OrElse Not parentsWithChildren.Contains(o)) _
.Select(Function(o) columns.Select(Function(c) _
o.AncestorsAndSelf() _
.OfType(Of JObject)() _
.Select(Function(parent) parent(c)) _
.OfType(Of JValue)() _
.Select(Function(v) CStr(v)) _
.FirstOrDefault()) _
.Reverse() _
.SkipWhile(Function(s) s Is Nothing) _
.Reverse())
Dim csvRows = { columns.AsEnumerable() }.Concat(rows) _
.Select(Function(r) String.Join(",", r))
Dim csv = String.Join(vbLf, csvRows)
这篇关于将LINQ-to-JSON查询从C#转换为VB.NET后,如何解决InvalidCastException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!