将两个JSON对象合并到ASP.NET中的新排序列表中

时间:2017-01-05 13:19:09

标签: asp.net json vb.net

我有两个FB页面提要,我试图将它们连接在一个对象(或列表或数组)中,我可以阅读,排序在" created_time"数据。我在评论后更改了问题代码。

这是我的JSON数据:

{
   "data": [
      {
         "message": "Zimovanje u punom tijeku :-)",
         "created_time": "2017-01-04T10:06:57+0000",
         "type": "photo",
         "name": "Photos from Odred izvi\u0111a\u010da Javor's post",
         "id": "217384491624554_1572127976150192"
      },
      {
         "message": "Skup\u0161tina Odreda izvi\u0111a\u010da tijeku...",
         "created_time": "2016-12-22T19:52:12+0000",
         "type": "photo",
         "name": "Timeline Photos",
         "id": "217384491624554_1552374844792172"
      },
    ...

这是我的代码,直到现在:

Public Class FBData
    Public Property data As New List(Of FBFeed)
End Class

Public Class FBFeed
    Public Property message As String
    Public Property created_time As DateTime
    Public Property id As String
    Public Property type As String
    Public Property name As String
End Class

Public Shared Function GetPosts( PageId As String, accessToken As String ) As FBData

    Dim APIlink As String = "https://graph.facebook.com/" & pageID & "/posts?fields=full_picture,message,created_time,id,link,type,name,description&access_token=" & accessToken

    Dim client As New WebClient()
    client.Encoding = System.Text.Encoding.UTF8
    Dim strJson As [String] = client.DownloadString(APIlink)

    Dim result As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)( strJson )

    Return result

End Function

在主代码中我调用了这个函数:

Dim array1 As FBData = GetPosts ( "OI.Plavipingvin", accessToken )
Dim array2 As FBData = GetPosts ( "217384491624554", accessToken )

'Merging two lists
array1.data.AddRange(array2.data.ToArray)

'Order final list
Dim OrderedPosts as List(Of FBFeed) = array1.data.OrderByDescending(Function(x) x.created_time) 

For Each Msg As FBFeed In array1.data
    Response.Write( Msg.created_time & "<br />" )
    Response.Write( "<image width=""100px"" height=""100px"" src=""" & Msg.full_picture & """><br />" )
Next

Dim OrderedPosts as List行会产生错误System.InvalidCastException: Unable to cast object of type 'System.Linq.OrderedEnumerable 2[_feed+FBFeed,System.DateTime]' to type 'System.Collections.Generic.List 1[_feed+FBFeed]'.

3 个答案:

答案 0 :(得分:1)

我不得不清理并清理您的样本数据,但想出了这个。获得初始对象MyData后,可以将后续JSON消息添加到列表data。希望这能为您提供所需的线索:

Module Module1

    Sub Main()
        Dim JsonSample1 As String = "{'data': [
      {
         'message': 'Zimovanje u punom tijeku :-)',
         'created_time': '2017-01-04T10:06:57+0000',
         'type': 'photo',
         'name': 'Photos from Odred izvi\u0111a\u010da Javor\'s post',
         'id': '217384491624554_1572127976150192'
      }]}"

        Dim JsonSample2 As String = "{'data': [
      {
         'message': 'Skup\u0161tina Odreda izvi\u0111a\u010da tijeku...',
         'created_time': '2016-12-22T19:52:12+0000',
         'type': 'photo',
         'name': 'Timeline Photos',
         'id': '217384491624554_1552374844792172'
      }]}"


        Dim MyData As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)(JsonSample1)
        Dim MyData1 As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)(JsonSample2)

        MyData.data.AddRange(MyData1.data.ToArray)

        Debug.Print("Msg Count: {0}", MyData.data.Count.ToString)
        For Each Msg As FBFeed In MyData.data
            Debug.Print("{0}{1}{2}", Msg.created_time, vbTab, Msg.message)
        Next

        Debug.Print("")

        For Each Msg As FBFeed In MyData.data.OrderBy(Function(x) x.created_time)
            Debug.Print("{0}{1}{2}", Msg.created_time, vbTab, Msg.message)
        Next

        Debug.Print("")

        For Each Msg As FBFeed In MyData.data.OrderByDescending(Function(x) x.created_time)
            Debug.Print("{0}{1}{2}", Msg.created_time, vbTab, Msg.message)
        Next
    End Sub

    Public Class FBData
        Public Property data As New List(Of FBFeed)
    End Class

    Public Class FBFeed
        Public Property message As String
        Public Property created_time As DateTime
        Public Property id As String
        Public Property type As String
        Public Property name As String
    End Class

End Module

输出如下:

Msg Count: 2
01/04/2017 05:06:57 Zimovanje u punom tijeku :-)
12/22/2016 14:52:12 Skupština Odreda izviđača tijeku...

12/22/2016 14:52:12 Skupština Odreda izviđača tijeku...
01/04/2017 05:06:57 Zimovanje u punom tijeku :-)

01/04/2017 05:06:57 Zimovanje u punom tijeku :-)
12/22/2016 14:52:12 Skupština Odreda izviđača tijeku...

答案 1 :(得分:1)

鉴于OP的更新代码,这是使用SortedDictionary的替代解决方案。请注意,将会有一些丢弃的消息具有相同的created_time毫秒级。大多数情况下,这些可能是先前收到的消息,但可能会有一点巧合的丢失。

Imports Newtonsoft.Json
Imports System.Timers
Imports System.Net

Module Module2

    Friend WithEvents Timer1 As New Timers.Timer(5000)

    Private OrderedPosts As New SortedDictionary(Of DateTime, FBFeed)
    Private AccessToken As String = "Your Token Goes Here"

    Sub Main()
        Timer1.Enabled = True
        Console.ReadKey()
    End Sub

    Private Sub Timer1_Elapsed(sender As Object, e As ElapsedEventArgs) Handles Timer1.Elapsed
        GetPosts("OI.Plavipingvin", AccessToken)
        GetPosts("217384491624554", AccessToken)

        Debug.Print("Msg Count: {0}", OrderedPosts.Count.ToString)
        For Each Post As FBFeed In OrderedPosts.Values
            Debug.Print("{0}{1}{2}", Post.created_time, vbTab, Post.message)
        Next
        Debug.Print("")
    End Sub

    Private Sub GetPosts(PageId As String, accessToken As String)
        Dim APIlink As String = String.Format("https://graph.facebook.com/{0}/posts?fields=full_picture,message,created_time,id,link,type,name,description&access_token={1}", PageId, accessToken)

        Using WebClient As New WebClient()
            WebClient.Encoding = Text.Encoding.UTF8

            With JsonConvert.DeserializeObject(Of FBData)(WebClient.DownloadString(APIlink))
                For Each Post As FBFeed In .data
                    Try
                        OrderedPosts.Add(Post.created_time, Post)
                    Catch ex As Exception
                        Debug.Print("Duplicate post created_time: {0}", Post.created_time.ToString("O"))
                    End Try
                Next
            End With
        End Using
    End Sub

    Private Class FBData
        Public Property data As New List(Of FBFeed)
    End Class

    Private Class FBFeed
        Public Property message As String
        Public Property created_time As DateTime
        Public Property id As String
        Public Property type As String
        Public Property name As String
    End Class

End Module

答案 2 :(得分:0)

所以,感谢@MrGadget帮助我解决了我的问题,因为我无法在网络上的任何地方找到完整的解决方案。

Dim accessToken As String= appID & "|" & appSecret

Dim array1 As FBData = GetPosts ( "OI.Plavipingvin", accessToken )
Dim array2 As FBData = GetPosts ( "217384491624554", accessToken )

'Merging two lists
array1.data.AddRange(array2.data.ToArray)

'Order final list
'Dim OrderedPosts as List(Of FBFeed) = array1.data.OrderByDescending(Function(x) x.created_time)

For Each Msg As FBFeed In array1.data.OrderByDescending(Function(x) x.created_time)
    Response.Write( Msg.created_time & "<br />" )
    Response.Write( "<image width=""100px"" height=""100px"" src=""" & Msg.full_picture & """><br />" )
Next

这里有FBData Class和函数来获取和序列化JSON。

Public Class FBData
    Public Property data As New List(Of FBFeed)
End Class

Public Class FBFeed
    Public Property full_picture As String
    Public Property message As String
    Public Property created_time As DateTime
    Public Property id As String
    Public Property link As String
    Public Property type As String
    Public Property name As String
    Public Property description As String
End Class

Public Shared Function GetPosts( PageId As String, accessToken As String ) As FBData

    Dim APIlink As String = "https://graph.facebook.com/" & pageID & "/posts?fields=full_picture,message,created_time,id,link,type,name,description&access_token=" & accessToken

    Dim client As New WebClient()
    client.Encoding = System.Text.Encoding.UTF8
    Dim strJson As [String] = client.DownloadString(APIlink)

    Dim result As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)( strJson )

    Return result

End Function