将标准EF列表转换为嵌套JSON

公正学习

我的ASPX页中有一个WEB方法,该方法使用实体框架从SQL DB检索列表。

    Using rep As New RBZPOSEntities
        q = rep.getSalesByLocation(fDate, tDate).ToList
    End Using

之后,我使用javascriptserializer将此列表转换为JSON字符串

    Dim jss As JavaScriptSerializer = New JavaScriptSerializer()
    Dim json As String = jss.Serialize(q)

因此,上述方法效果很好,我可以在客户端使用AJAX来成功显示结果。

我现在遇到的问题是将平面列表转换为嵌套JSON字符串。因此,请考虑以下列表:

locationName as string
MonthName as string
totalAmount as string

需要将其转换为这样的JSON:

[{locationName:'Tokyo',totalAmount:[100,200,300,400]},
 {locationName:'New York',totalAmount:[500,600,700,800]}]

因此,上述情况下的totalAmount值对应于特定月份某个位置的totalAmounts。例如,东京在一月的总金额是100,二月的总金额是200,依此类推。

我能做什么:我可以创建一个嵌套列表,并用EF的结果填充它,然后序列化为JSON。

我要问的还有其他更清洁的方法可以做到这一点。

谢谢

尤金·蒂姆(Eugene Timm)

正如Todd已经说过的,您需要将平面列表转换为另一种中间类型的列表。让我们将现有的Type称为“ InputType”,并将您想要的Type称为“ OutputType”

Public Class InputClass
  Public locationName as String
  Public MonthName as String
  Public totalAmount as String
End Class

Public Class OutputClass
  Public LocationName As String
  Public TotalAmount As List(Of String)

  Public Sub New(groupedInputClass As IGrouping(Of String, InputClass))
    LocationName = groupedInputClass.Key
    TotalAmount = groupedInputClass.Select(Function(x) x.totalAmount).ToList()
  End Sub
End Class

然后,您所需要做的就是将InputType列表转换为OutputType列表,而使用LINQ确实很容易。

Public Class MappingHelper
  Public Function Map (inputList as List(Of InputClass)) As List(Of OutputClass)

    Dim groupedByLocation = inputList.GroupBy(Function(k) k.LocationName)

    Dim nestedLocations = groupedByLocation.Select(Function(x) new OutputClass(x)).ToList()

    Return nestedLocations
  End Function
End Class

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章