【问题标题】:Convert a standard EF list to a nested JSON将标准 EF 列表转换为嵌套 JSON
【发布时间】:2015-12-15 16:31:40
【问题描述】:

我的 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。

我在问什么: 还有其他更清洁的方法吗?

谢谢

【问题讨论】:

    标签: asp.net json ajax serialization webmethod


    【解决方案1】:

    正如 Todd 已经说过的,您需要将平面列表转换为另一种中间类型的列表。让我们将您现有的类型称为“InputType”,将您想要的类型称为“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
    

    【讨论】:

    • 我知道这个问题已经很久没有回答了,但我遇到了你的解决方案的问题。使用您的答案,我得到的 TotalAmount 为空。如果需要,我可以发布我的代码
    【解决方案2】:

    如果您使用中间类型,它可能会有所帮助。比如:

    class RbzposInfo {
      public string Location {get;set;}
      public List<MonthlyRevenue> Monthlies {get;set;}
    }
    
    class MonthlyRevenue {
      public string Month {get;set;}
      public int Revenue {get;set;}
    }
    
    var result = new List<RbzposInfo>(); 
    foreach (var r in q) {  // q from your code
       var info = new RbzposInfo();
       // TODO: put r values into info.
       result.Add(info);
    }
    Dim json As String = jss.Serialize(result);
    

    (PS,对不起,我在你身上混合了 .NET 语言。我的代码是 C#。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2020-05-13
      • 2010-11-15
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多