【问题标题】:Combine one field in a JSON object array to comma-delimited string in ASP.NET在 ASP.NET 中将 JSON 对象数组中的一个字段组合成逗号分隔的字符串
【发布时间】:2015-09-04 06:21:22
【问题描述】:

我有一个这样的 JSON 对象数组,它是从客户端通过 AJAX 提供的。

[{"aid":"6038","testid":"162","testtype":"0"},
{"aid":"6037","testid":"162","testtype":"1"},
{"aid":"5763","testid":"162","testtype":"0"},
{"aid":"5772","testid":"162","testtype":"1"},
{"aid":"5773","testid":"162","testtype":"1"}]

我有一个服务器端类来反序列化上述 JSON,如下所示。

Public Class ComparisonAttributes
    Public testid, attributeid, testtype As Integer
End Class

所以我将 JSON 反序列化为

 Dim ca() As ComparisonAttributes
 ca = js.Deserialize(Of ComparisonAttributes())(attributes)

所以我得到了真正的 JSON 对象数组。

但我的要求是根据 testtype=1

之类的条件将 JSON 对象中的所有 aid 组合成逗号分隔的字符串

所以结果应该是 6037,5772,5773

我能够使用这样的 JSON 对象循环来实现这一点

For Each cad As ComparisonAttributes In ca
   ''' Here i did the condition check and append to a string array
Next

但我相信有一种方法,就像我们使用 LINQ 或类似方式在 Datatable 中组合行而不使用循环

【问题讨论】:

    标签: asp.net json vb.net linq


    【解决方案1】:

    这样的 LINQ 查询可能会有所帮助:

    Dim result = ca.Where(Function(item) item.testtype = 1).Select(Function(item) item.aid).ToArray()
    

    或类似的东西:

    Dim result = (From ca In item Where item.testtype = 1item.aid).ToArray()
    

    【讨论】:

    • 不幸的是,这在最后一个整数部分显示为错误 Dim result = ca.Where(Function(item) item.testtype = 1).Select(Function(item) item.attributeid).ToArray(Of Integer)() 在“Of Integer”处出现类似“enumerable is not generic and cannot have type arguments”的错误
    • 尝试隐式转换。我刚刚更新了答案
    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    相关资源
    最近更新 更多