none
extract Json data by webscoket RRS feed

  • Question

  • Dear

      Cloud you please show me example how read Json data by websocket  either by C# or VB.net

      thank you in advance 

    Sunday, August 13, 2017 11:47 AM

All replies

  • Why can't you use Bing or Google and go find an example yourself?
    Sunday, August 13, 2017 12:32 PM
  • No matter where the data is coming from, json is a string which needs to be deserialized where I generally use Newtonsoft library which is installed via NuGet package manager in Visual Studio.

    using the following tool, paste your json into the tool. The tool creates classes to represent your json data.

    Place the class into the project, get the data back from the websocket, use (I typed this in from memory so hopefully it's correct)

    Newtonsoft.Json.JsonConvert.DeserializeObject(Of YourClassGoesHere)(jsonData)

    YourClassGoesHere is the class generated by the tool, jsonData is the string returned by the call from web socket.

    Note the class generated by the tool will put the following on each member


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, August 13, 2017 1:31 PM
    Moderator
  • Don't like to just interject but there is no tool required.  VS will create the classes for you.  Just open up a new class window, delete the contents then use the Paste/Special from the VS edit menu.  It allows you to paste JSon and also XML to create the classes that serialization/deserialization would use.

    Lloyd Sheen

    Sunday, August 13, 2017 6:04 PM
  • Don't like to just interject but there is no tool required.  VS will create the classes for you.  Just open up a new class window, delete the contents then use the Paste/Special from the VS edit menu.  It allows you to paste JSon and also XML to create the classes that serialization/deserialization would use.

    Lloyd Sheen

    Forgot all about this feature, used it many years ago too.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, August 13, 2017 9:14 PM
    Moderator
  • Dear

      Cloud you please show me example how read Json data by websocket  either by C# or VB.net

      thank you in advance 

    I'll explain in more detail tomorrow if you're interested, but the following will read an XML file that I have on my site, and from that create a collection of instances of people's information. Not to worry - the data is totally fake!

    Once that's done, using NewtonSoft (as Karen explained) I'll then have it write out a JSON file that I put on my desktop. I subsequently uploaded the JSON file to my site and the next part of the code reads the JSON online via a WebRequest and parses the data back into instances of the people's information:

    Code For Example Class:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    Imports Newtonsoft.Json
    
    Public Class PersonData
        Private Shared _data As List(Of PersonData)
    
        Public Shared ReadOnly Property Collection As IEnumerable(Of PersonData)
            Get
                Return _data.ToArray
            End Get
        End Property
    
        Public Sub New()
            _data = New List(Of PersonData)
        End Sub
    
        Public Property FirstName As String
        Public Property MiddleInitial As String
        Public Property LastName As String
        Public Property StreetAddress As String
        Public Property City As String
        Public Property State As String
        Public Property ZipCode As String
        Public Property Email As String
    
        Public Sub GetDataFromXML(ByVal url As String)
    
            If Not String.IsNullOrWhiteSpace(url) Then
                Try
                    Dim xDoc As XElement = XElement.Load(url)
                    Dim tempList As New List(Of PersonData)
    
                    For Each xData As XElement In xDoc...<Person>
                        tempList.Add(New PersonData _
                                     With {.FirstName = xData...<FirstName>.Value, _
                                           .MiddleInitial = xData...<MiddleInitial>.Value, _
                                           .LastName = xData...<LastName>.Value, _
                                           .StreetAddress = xData...<StreetAddress>.Value, _
                                           .City = xData...<CityName>.Value, _
                                           .State = xData...<StateName>.Value, _
                                           .ZipCode = xData...<ZipCode>.Value, _
                                           .Email = xData...<EmailAddress>.Value})
                    Next
    
                    If tempList.Count > 0 Then
                        _data = tempList
                    End If
    
                Catch ex As Exception
                    Throw
                End Try
            End If
    
        End Sub
    
        Public Sub ExportToJSON(ByVal localFilePath As String)
    
            Try
                If Not String.IsNullOrWhiteSpace(localFilePath) Then
                    If _data.Count > 0 Then
                        Dim fi As New FileInfo(localFilePath)
    
                        If fi.Exists Then
                            fi.Delete()
                        End If
    
                        Dim sb As New System.Text.StringBuilder(JsonConvert.SerializeObject(_data))
    
                        If sb.Length > 0 Then
                            File.WriteAllText(fi.FullName, sb.ToString)
                        End If
                    End If
                End If
    
            Catch ex As Exception
                Throw
            End Try
    
        End Sub
    
        Public Sub ImportFromJSON(ByVal jsonURL As String)
    
            Try
                If Not String.IsNullOrWhiteSpace(jsonURL) Then
                    Dim jText As String = GetTextFromURL(jsonURL)
    
                    If Not String.IsNullOrWhiteSpace(jText) Then
                        Dim people() As PersonData = JsonConvert.DeserializeObject(Of PersonData())(jText)
    
                        If people IsNot Nothing AndAlso people.Length > 0 Then
                            _data = New List(Of PersonData)
    
                            For Each pd As PersonData In people
                                _data.Add(pd)
                            Next
                        End If
                    End If
                End If
    
            Catch ex As Exception
                Throw
            End Try
    
        End Sub
    
        Private Function _
           GetTextFromURL(ByVal url As String, _
                          Optional ByVal timeoutMS As Integer = 500) As String
    
            Dim retVal As String = Nothing
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
                request.Timeout = timeoutMS
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using reader As New StreamReader(dataStream)
                            Dim responseFromServer As String = reader.ReadToEnd()
                            retVal = responseFromServer
                        End Using
                    End Using
                End Using
    
            Catch ex As System.Net.WebException
                ' Intentionally empty: Be sure to test
                ' the return value.
    
            Catch ex As Exception
                MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
                                              vbCrLf, ex.Message), _
                                              "Exception Thrown", _
                                              MessageBoxButtons.OK, _
                                              MessageBoxIcon.Warning)
            End Try
    
            Return retVal
    
        End Function
    End Class

    I tested it in Form1:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Public Class Form1
        Dim _desktop As String = _
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    
        Private Sub Form1_Load(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                               Handles MyBase.Load
    
            Const xmlURL As String = _
                "http://www.fls-online.net/VBNet_Forum/SampleData/Sample_Data_100.xml"
    
            Dim pd As New PersonData
            pd.GetDataFromXML(xmlURL)
    
            Dim jsonFilePath As String = _
                IO.Path.Combine(_desktop, "ExampleJSON.txt")
    
            pd.ExportToJSON(jsonFilePath)
    
            Const jsonURL As String = _
                "http://www.fls-online.net/VBNet_Forum/SampleData/ExampleJSON.txt"
    
            pd.ImportFromJSON(jsonURL)
    
            Stop
    
        End Sub
    
    End Class

    Everything there will work - the data is "live". I don't have an uploader in the class but other than that, you can duplicate it.

    The XML is shown here:

    http://www.fls-online.net/VBNet_Forum/SampleData/Sample_Data_100.xml

    ...and the resultant JSON of that same data is shown here:

    http://www.fls-online.net/VBNet_Forum/SampleData/ExampleJSON.txt

    You can get a sense of why JSON is catching on just by looking at the latter. Let me know if you're interested and we'll talk more about the details.

    I hope this helps. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, August 13, 2017 10:42 PM
  • Hi Abdullfattah,

    If you want to use webscoket, it seems that you need to server and client. the following link provide related sample about webscoket server and client

    #Server.

    https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server

    #Client

    https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications

    Note:This response contains a reference to a third party World Wide Web site.Microsoft is providing this information as a convenience to you.

    Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there.

    There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

    Best regards,

    Cole


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, August 25, 2017 7:37 AM
    Moderator