getting errore parsing a json file - vb.net

i'm trying to extract data from a json file received from a web.i used newtonsoft library
i'm using this code :
Dim JSONtxt As String = File.ReadAllText("c:\temp\prova.json")
Dim account As Person = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Person)(JSONtxt)
the class is :
Public Class Person
Public Property validationType As String
Public Property lastName As String
Public Property firstName As String
End Class
unfortunately account does not get any value....
how can be ??
thanks for you help
this is my json :
{"listReservationReport":[{"validationType":"PRESENTE","bookingId":"xxxxx","travelId":null,"travelSolutionId":null,"couponId":"xxxxxx","transportMeanName":"aereo","transportClassification":"az","transportMeanDate":"16-01-2020","couponServiceType":"Posto a sedere","materializationType":"NON MATERIALIZZATO","fila":"6","seat":"2A","pnrCode":"xxxxxx","departureLocationName":"NAPOLI capodichino","arrivalLocationName":"ROMA fiumicino","cpCode":"xxxxxxx","offerName":"Super Economy","serviceLevel":"2° Premium","amount":"109,90","adults":1,"teens":0,"alreadyPaied":"--","alreadyCached":"--","ci204":"PRESENTE","firstName":"xxxxxxxx","lastName":"xxxxxx","channelName":"Internet B2C","gender":"Non disponibile","saleSystem":"galileo","travellerInfo":null,"validation":null},{"validationType":"PRESENTE","bookingId":"xxxxx","travelId":null,"travelSolutionId":null,"couponId":"xxxxxx","transportMeanName":"aereo","transportClassification":"az","transportMeanDate":"16-01-2020","couponServiceType":"Posto a sedere","materializationType":"NON MATERIALIZZATO","fila":"6","seat":"2A","pnrCode":"xxxxxx","departureLocationName":"NAPOLI capodichino","arrivalLocationName":"ROMA fiumicino","cpCode":"xxxxxxx","offerName":"Super Economy","serviceLevel":"2° Premium","amount":"109,90","adults":1,"teens":0,"alreadyPaied":"--","alreadyCached":"--","ci204":"PRESENTE","firstName":"xxxxxxxx","lastName":"xxxxxx","channelName":"Internet B2C","gender":"Non disponibile","saleSystem":"galileo","travellerInfo":null,"validation":null},{"validationType":"PRESENTE","bookingId":"xxxxx","travelId":null,"travelSolutionId":null,"couponId":"xxxxxx","transportMeanName":"aereo","transportClassification":"az","transportMeanDate":"16-01-2020","couponServiceType":"Posto a sedere","materializationType":"NON MATERIALIZZATO","fila":"6","seat":"2A","pnrCode":"xxxxxx","departureLocationName":"NAPOLI capodichino","arrivalLocationName":"ROMA fiumicino","cpCode":"xxxxxxx","offerName":"Super Economy","serviceLevel":"2° Premium","amount":"109,90","adults":1,"teens":0,"alreadyPaied":"--","alreadyCached":"--","ci204":"PRESENTE","firstName":"xxxxxxxx","lastName":"xxxxxx","channelName":"Internet B2C","gender":"Non disponibile","saleSystem":"galileo","travellerInfo":null,"validation":null}],"validatorList":[{"firstName":"xxxxx","lastName":"xxxx","roleId":"USR","enterpriseRoleType":"CST"},{"firstName":"xxxx ","lastName":"xxxx ","roleId":"xxx","enterpriseRoleType":"CT"},{"firstName":"x","lastName":"xxxx ","roleId":"USR","enterpriseRoleType":"CPV"},{"firstName":"xxx","lastName":"xxx","roleId":"USR","enterpriseRoleType":"CT"}],"materializedStatus":[{"onboard":30,"absent":0,"none":1,"defect":0,"undo":0}],"notMaterializedStatus":[{"onboard":522,"absent":0,"none":110,"defect":0,"undo":0}]}

Alright, give this a try....
Imports System.Linq
Imports BVSoftware.Bvc5.Core
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.IO
Imports System.Collections.ObjectModel
Partial Class _testPW22
Inherits System.Web.UI.Page
Private Class Person
Public Property validationType As String
Public Property lastName As String
Public Property firstName As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim JSONtxt As String = File.ReadAllText("c:\temp\prova.json")
Dim ob As JObject = JObject.Parse(JSONtxt)
Dim persons As New Collection(Of Person)()
For Each item As JObject In ob.SelectToken("listReservationReport")
Dim test As Person = JsonConvert.DeserializeObject(Of Person)(item.ToString())
persons.Add(test)
Next
End Sub
End Class

Related

Class marked for Deliminted but error says not

I have the dubious task of upgrading an old vb app which is using file helpers but for some reason, it appears to be ignoring the fact that I have marked it as a delimited record.
In the form it is using the following to attach the csv file to the record which is simlar to how c# does it.
Private Sub browseButton_Click(sender As System.Object, e As System.EventArgs) _
Handles browseButton.Click
Try
Dim file = GetFile()
'' Errors
Dim errors As New Dictionary(Of Integer, String)
If IO.File.Exists(file) Then
Dim engine As New FileHelperEngine(Of AveryOrderCsv)
_records = CType(engine.ReadFile(file), AveryOrderCsv()).ToList()
Dim count As Integer = 0
Dim success As Integer = 0
For Each averyOrderCsv As AveryOrderCsv In _records
Try
ImportProgressBar.Value = count
ImportProgressLabel.Text = String.Format("Importing {0} of {1} dockets",
count + 1, _records.Count())
System.Windows.Forms.Application.DoEvents()
If CreateSop(averyOrderCsv) Then
success = success + 1
End If
Catch ex As Exception
errors.Add(count, ex.Message)
End Try
count = count + 1
Next
End If
Catch ex As Exception
ExceptionManager.HandleUnexpectedException(ex)
End Try
The Class
Imports AveryIntegration.Common.CSV
Imports FileHelpers
Imports System
Imports System.Diagnostics
Namespace AveryIntegration.Common.CSV.Records
<DelimitedRecord(",")>
Public Class AveryOrderCsv
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String2 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String3 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String4 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String5 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String10 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String15 As String
Public Decimal1 As Decimal
Public Decimal5 As Decimal
Public Decimal8 As Decimal
Public Decimal9 As Decimal
Public Decimal10 As Decimal
Public Date1 As DateTime
Public Ticket2 As Integer
<DebuggerNonUserCode>
Public Sub New()
MyBase.New()
End Sub
End Class
End Namespace
The error that I am getting is the following but as you see from above i have declared it as a delimited record and imported the imports FileHelpers
In VB the attribute must be on the same logical line.
<DelimitedRecord(",")> Public Class AveryOrderCsv
or
<DelimitedRecord(",")> _
Public Class AveryOrderCsv
Same thing for the properties.
The article Applying Attributes says:
In Visual Basic, the attribute is surrounded by angle brackets and must be on the same logical line; the line continuation character can be used if a line break is desired.

Converting a class with a property of T to and from json

I have a class (MyMessage) which have a property called "Settings" of Type T.
I need to convert MyMessage to json, send it via TCP and when I recieve it, I need to test what class Type T is and then convert the recieved json to the MyMessage Of T class.
This is my code so far - function SendMessage and MessageRecieved is not working ... and I need your help :)...
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim t As New MyMessage(Of MyMessageSettingsText)
t.Settings.Text = "Yes"
Call SendMessage(t)
Dim n As New MyMessage(Of MyMessageSettingsNumber)
n.Settings.Number = 1
Call SendMessage(n)
End Sub
Private Sub SendMessage(msg As MyMessage)
Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(msg)
' Do send using tcp etc
End Sub
Private Sub MessageRecieved(msgJson As String) ' A json string recived from a tcp server
Dim msg As MyMessage = DirectCast(Newtonsoft.Json.JsonConvert.DeserializeObject(Of MyMessage)(msgJson), MyMessage)
If TypeOf (msg.Settings) Is MyMessageSettingsText Then
Dim t As MyMessage(Of MyMessageSettingsText) = CType(msg, MyMessage(Of MyMessageSettingsText))
' do something with t
End If
End Sub
End Class
Public MustInherit Class MyMessageSettingsBase
End Class
Public Class MyMessageSettingsText
Inherits MyMessageSettingsBase
Public Property Text As String
End Class
Public Class MyMessageSettingsNumber
Inherits MyMessageSettingsBase
Public Property Number As Integer
End Class
Public Class MyMessage(Of T As {New})
Public Property Name As String
Public Property Settings As New T
End Class

Deserialize to class

I have a class Person which I can serialize with the following code, but I can’t figure out how to deserialize the file back to the class.
I would be grateful for help on this. Thank you.
Imports Newtonsoft.Json
Imports Windows.Storage
Imports Windows.Storage.Streams
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Gender As String
End Class
Public NotInheritable Class MainPage
Inherits Page
Private p As Person
Private pList As New List(Of Person)
Private Async Sub Save()
Dim jsonContents As String = JsonConvert.SerializeObject(pList)
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim textFile As StorageFile = Await localFolder.CreateFileAsync("a.txt", CreationCollisionOption.ReplaceExisting)
Using textStream As IRandomAccessStream = Await textFile.OpenAsync(FileAccessMode.ReadWrite)
Using textWriter As New DataWriter(textStream)
textWriter.WriteString(jsonContents)
Await textWriter.StoreAsync()
End Using
End Using
End Sub
End Class
I tried the following but it doesn’t work.
Private Async Sub GetData()
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim textFile = Await localFolder.GetFileAsync("a.txt")
Dim readFile = Await FileIO.ReadTextAsync(textFile)
Dim obj As RootObject = JsonConvert.DeserializeObject(Of RootObject)(readFile)
End Sub
Public Class RootObject
'Public Property pList1() As List(Of Person)
Public Property Name() As String
Public Property Age() As Integer
Public Property Gender() As String
End Class
You should make sure your VB class object's property in accordance with the JSON key or JSON name.
For example using your sample JSON data in your comment:
Since your JSON data is not complete, I modify it as the following:
{"pList1":[{"Name":"Henrik","Age":54,"Gender":"Mand"},{"Name":"Lone","Age":50,"Gender":"Kvinde"},{"Name":"Niels","Age":24,"Gender":"Mand"},{"Name":"Pernille","Age":26,"Gender":"Kvinde"}]}
You can keep the above Json data in a file named my.txt, if you want to deserialize the Json data to VB object, your VB objects classes should be as the following two classes:
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Gender As String
End Class
Public Class RootObject
Public Property pList1() As List(Of Person)
End Class
Please pay attention to that: the pList1 property of RootObject class is corresponding to the pList1 key or name in the JSON data.
Then you should be able to use the JsonConvert class to deserialize to RootObject.
Private Async Sub GetData()
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim textFile = Await localFolder.GetFileAsync("my.txt")
Dim readFile = Await FileIO.ReadTextAsync(textFile)
Dim obj As RootObject = JsonConvert.DeserializeObject(Of RootObject)(readFile)
End Sub

How to display public variables in another form

I've already searched this up many times but none of them worked for me so please help. The code I've been trying to use is:
'Making the variables public in form2
Public Module GlobalVariables
'Making the variables public
Public Property Juvenplp As Integer
Public Property Adultplp As Integer
Public Property Senileplp As Integer
Public Property Juvensr As Single
Public Property Adultsr As Single
Public Property Senilesr As Single
Public Property Birthrate As Single
Public Property genmore As Integer
Public Property i As Integer
End Module
Displaying then in Form4
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
InitializeComponent()
GlobalVariables.Juvenplp = Me.Label7.Text
GlobalVariables.Adultplp = Me.Label8.Text
GlobalVariables.Senileplp = Me.Label9.Text
GlobalVariables.Juvensr = Me.Label10.Text
GlobalVariables.Adultsr = Me.Label11.Text
GlobalVariables.Senilesr = Me.Label12.Text
GlobalVariables.Birthrate = Me.Label14.Text
End Sub
The problem is that they're not being displayed.

Entity Framework : Error when trying to Deep clone an object

I'm using Entity Framework 6 , with Database First. The model is created using wizard from existing Sql server database.
I'm using this code to do a deep clone :
Imports System.ComponentModel
Imports System.Collections
Imports System.Data.Entity.Core.Objects.DataClasses
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Reflection
Imports System.Runtime.CompilerServices
Module Extensions
Private Function ClearEntityObject(Of T As Class)(ByVal source As T, ByVal bCheckHierarchy As Boolean) As T
If (source Is Nothing) Then
Throw New Exception("Null Object cannot be cloned")
End If
Dim tObj As Type = source.GetType
If (Not tObj.GetProperty("EntityKey") Is Nothing) Then
tObj.GetProperty("EntityKey").SetValue(source, Nothing, Nothing)
End If
If bCheckHierarchy Then
Dim PropertyList As List(Of PropertyInfo) = Enumerable.ToList(Of PropertyInfo)((From a In source.GetType.GetProperties
Where a.PropertyType.Name.Equals("ENTITYCOLLECTION`1", StringComparison.OrdinalIgnoreCase)
Select a))
Dim prop As PropertyInfo
For Each prop In PropertyList
Dim keys As IEnumerable = DirectCast(tObj.GetProperty(prop.Name).GetValue(source, Nothing), IEnumerable)
Dim key As Object
For Each key In keys
Dim childProp As EntityReference = Enumerable.SingleOrDefault(Of PropertyInfo)((From a In key.GetType.GetProperties
Where (a.PropertyType.Name.Equals("EntityReference`1", StringComparison.OrdinalIgnoreCase))
Select a)).GetValue(key, Nothing)
ClearEntityObject(childProp, False)
ClearEntityObject(key, True)
Next
Next
End If
Return source
End Function
<Extension()> _
Public Function ClearEntityReference(ByVal source As Object, ByVal bCheckHierarchy As Boolean) As Object
Return ClearEntityObject(source, bCheckHierarchy)
End Function
<Extension()> _
Public Function Clone(Of T)(ByVal source As T) As T
Dim ser As New DataContractSerializer(GetType(T))
Using stream As MemoryStream = New MemoryStream
ser.WriteObject(stream, source)
stream.Seek(0, SeekOrigin.Begin)
Return DirectCast(ser.ReadObject(stream), T)
End Using
End Function
End module
Now , I try to use this code like this :
Private Sub DoClone
Dim litm, newitm As MyObject
litm = context.MyObjects.FirstOrDefault
newitm = litm.Clone()
newitm.ClearEntityReference(True)
context.MyObjects.Add(newitm)
context.SaveChanges()
End Sub
I get an error :
An unhandled exception of type
'System.Runtime.Serialization.SerializationException' occurred in
System.Runtime.Serialization.dll
Additional information:Type
'System.Data.Entity.DynamicProxies.MyObject_F2FFE64DA472EB2B2BDF7E143DE887D3845AD9D1731FD3107937062AC0C2E4BB'
with data contract name
'MyObject_F2FFE64DA472EB2B2BDF7E143DE887D3845AD9D1731FD3107937062AC0C2E4BB:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected.
Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
This is my model that I use :
Partial Public Class Myobject
Public Property id As Integer
Public property name as string
Public Overridable Property chld As ICollection(Of chld) = New HashSet(Of chld)
Public Overridable Property chld1 As ICollection(Of chld1) = New HashSet(Of chld1)
End Class
Partial Public Class chld
Public Property id As Integer
Public Property date1 as DateTime
Public Property quantity as Integer
Public Property ParentID as integer
Public Overridable Property MyObj1 As MyObject
End Class
Partial Public Class chld1
Public Property id As Integer
Public Property nm as string
Public Property ParentID as integer
Public Overridable Property MyObj1 As MyObject
End Class