Newton.Json.DeserializeObject vb.net - json

I'm new trying to use Newton.Json.ConvertObject with VB.net
If someone could tell me how to use it and put my JSON into an array, this is my file:
{
"nombre":
["Alex","Carlos","Diego","Laura","Nancy"]
}
and I tried to use:
Public Class objMarcas
Public Property marca() As String
End Class
Dim fileMarcas As String = System.IO.File.ReadAllText("C:\instAplicativoCCR\marcas.json")
Dim arrMarcas As objMarcas
arrMarcas = JsonConvert.DeserializeObject(Of objMarcas)(fileMarcas)

To match your JSON format,
Public Class objMarcas
Public Property nombre() As List(Of String)
End Class
Then you do a foreach loop to get the string in the list. (You may want to check if arrMarcas is null and arrMarcas.nombre.Count is greater than 0 before calling the foreach loop)
For Each s As String In arrMarcas.nombre
'Console.WriteLine(s)
Next

Related

Deserialize JSON with vb.net

This is my manually created class
Public Class ZohoList
Public Property Select_Store() As String
Get
Return m_Select_Store
End Get
Set
m_Select_Store = Value
End Set
End Property
Private m_Select_Store As String
End Class
Public Class RootObject
Public Property Zoho_List As List(Of ZohoList)
Get
Return m_Zoho_List
End Get
Set
m_Zoho_List = Value
End Set
End Property
Private m_Zoho_List As List(Of ZohoList)
End Class
After i get JSON response like this
{
"Store_Money_Snapshot":[
{
"TODO":"YES",
"Date_field":"10-May-2018",
"Xpawn_Money":"3562",
"Select_Store":"TEST",
"Total_Counted_Money":"$ 3,000.00",
"Store_from_Xpawn_pc2":"TEST",
"Discrepancy_Amount":"$ -562.00",
"Store_Problem_fixed":"NO",
"ID":"1111111111111111111",
"Image":"",
"Store_Closing_Balance":"$ 33,482.00"
},
{
"TODO":"YES",
"Date_field":"10-May-2018",
"Xpawn_Money":"10234",
"Select_Store":"TEST2",
"Total_Counted_Money":"$ 9,800.00",
"Store_from_Xpawn_pc2":"TEST2",
"Discrepancy_Amount":"$ -434.00",
"Store_Problem_fixed":"NO",
"ID":"2222222222222",
"Image":"",
"Store_Closing_Balance":"$ 33,482.00"
}
]
}
My vb.net code for deserializing object is put in two lines
Dim myO = JsonConvert.DeserializeObject(Of RootObject)(response)
Dim items = myO.Zoho_List
For Each item In items
lTodo.Add(item.Select_Store.ToString)
'Now comes th code
Next
From entire response i only need the Select_Store value so in class i put only that value
Also i tried put all values in my class but still it wont deserialize JSON response
Your RootObject is paired with the first curly brace {.
There is then one property on that "root object' in the json: Store_Money_Snapshot, which doesn't appear anywhere in your RootObject.
Store_Money_Snapshot is an array or List<> or objects. These objects contain your Select_Store property.
So something like this should get you moving:
Public Class RootObject
' RootObject is a HORRIBLE name.
Public Property Store_Money_Snapshot As List(Of ZohoList)
End Class
Public Class ZohoList
' Again, ZohoList is a HORRIBLE name.
Public Property Select_Store As String
End Class
I strongly encourage you to give some thought to naming your classes with more accurate descriptive names.

How to parse Poloniex Json into VB Net Object?

I'm currently pulling in the Poloniex returnCompleteBalances info in the following JSON format:
{"LTC":{"available":"5.015","onOrders":"1.0025","btcValue":"0.078"},"NXT:{...} ... }
I am trying to add the info to a class I made, and separate the different coins(property names) and their associated info. So far I have the following:
Sub GetBalances()
Dim method As String = calldata("returnCompleteBalances")
Dim allData As JObject = JObject.Parse(method)
Dim coinlist As New List(Of balancedata)
For Each token As JToken In allData("objects")
Dim prop As JProperty = token
coinlist.Add(New balancedata With {.Coin = prop.Name, .available = prop.Value("available"), .onOrders = prop.Value("onOrders"), .btcValue = prop.Value("btcValue")})
Next
End Sub
And the class
Public Class balancedata
Public Property Coin As String
Public Property available As Decimal
Public Property onOrders As Decimal
Public Property btcValue As Decimal
End Class
When I run the code, I receive an error on the for each token as Jtoken line that reads: "Object reference not set to an instance of an object"
How do I resolve this? I do not know all of the values for the property name, LTC, BTC, etc. so I am trying to look through them all and itemize the associated values into a list.

convert object json to object vb .net

Hello I need to convert this objetct to vb.
{"user":
[
{"name":"CompanyName"},
{"password":"CompanyPassword"},
{"email":"mail#company.com"},
{"name":"UserName"},
{"email":"user#mail.com"}
]
}
I try with this:
Public Class InfoObjUser
Public Property name As String
Public Property password As String
Public Property email As String
End Class
Public Class ObjUser
Public Property user As New List(Of InfoObjUser)
End Class
but when I go to serialize json object created in vb
I see that there are no curly brackets.
Also in vb I can't add {"name":"UserName"},{"email":"user#mail.com"}
because they are already present.
Take a look at this: JSON Serialization in .Net.
You need to add the System.Runtime.Serialization as reference to your project, and then set up a serializer object in your code. You also need to tag, which fields in your class match your JSON code.
This would be your class setup:
<DataContract>
Public Class InfoObjUser
<DataMember(Name:="Name")>
Public Property name As String
<DataMember(Name:="Password")>
Public Property password As String
<DataMember(Name:="Email")>
Public Property email As String
End Class
<DataContract>
Public Class ObjUser
<DataMember>
Public Property user As New List(Of InfoObjUser)
End Class
And a Json reader class for that would look like this:
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Json
Public Class JsonReader
Public Shared Function FromString(Of T)(ByVal input As String) As T
Dim serializer As New DataContractJsonSerializer(GetType(T))
Dim memStream As New MemoryStream()
Dim sw As New StreamWriter(memStream)
sw.Write(input)
sw.Flush()
memStream.Position = 0
Dim returnObj As T = CType(serializer.ReadObject(memStream), T)
Return returnObj
End Function
End Class
And finally, you can call this class like this:
Dim jsonString ' = ...Input string here
Dim user As ObjUser = JsonReader.FromString(Of ObjUser)(jsonString)
However, it is not possible to have the name for two different data objects, as the serializer would not know where to map them to, as it goes by Object name.
I don't know how established this data structure already is, but if it's possible, I would suggest you to change the duplicated names, as no real mapping can occur when doing so programmatically.
<DataMember(Name:="UserName")>
Public Property username As String
<DataMember(Name:="UserEmail")>
Public Property usermail As String
If you would add something like this to your data model class and rename the field names in your Json, then it would work.

Json parsing issue in vb.net

I need to parse following json in vb.net. I'm using Json.net but do not know how to do it.
Problem occurs in scan result contains scan detail that conaints anti virus name with some detail. but all the anti-virus is object not an array. So please any body tell me how to do it.
{"file_id":"aaa60a443e3a4426944da9e6fe8a3f3c","scan_results":{"scan_details":{"AegisLab":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Agnitum":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Ahnlab":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-24T00:00:00Z","scan_time":1.0},"Antiy":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"AVG":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Avira":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"BitDefender":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"ByteHero":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"ClamWin":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"CYREN":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"DrWebGateway":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Emsisoft":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"ESET":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Filseclab":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Fortinet":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"F-prot":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"F-secure":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"GFI":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Hauri":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Ikarus":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Jiangmin":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"K7":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-20T00:00:00Z","scan_time":1.0},"Kaspersky":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Lavasoft":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"McAfee-Gateway":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Microsoft":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"NANO":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"nProtect":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Preventon":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"QuickHeal":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Sophos":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"STOPzilla":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-21T00:00:00Z","scan_time":1.0},"SUPERAntiSpyware":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Symantec":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Tencent":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"TotalDefense":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"TrendMicro":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-21T00:00:00Z","scan_time":1.0},"TrendMicroHouseCall":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-21T00:00:00Z","scan_time":1.0},"VirIT":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-20T00:00:00Z","scan_time":1.0},"VirusBlokAda":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-20T00:00:00Z","scan_time":1.0},"Xvirus":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-23T00:00:00Z","scan_time":1.0},"Zillya!":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-22T00:00:00Z","scan_time":1.0},"Zoner":{"scan_result_i":0,"threat_found":"","def_time":"2015-02-18T00:00:00Z","scan_time":1.0}},"rescan_available":true,"data_id":"32fe182492834b6f88b1d95f6a14c886","scan_all_result_i":0,"start_time":"2015-02-23T13:10:55.549Z","total_time":1.0,"total_avs":43,"progress_percentage":100,"in_queue":0,"scan_all_result_a":"Clean"},"file_info":{"file_size":0,"upload_timestamp":"2015-02-23T00:40:41.029Z","md5":"D41D8CD98F00B204E9800998ECF8427E","sha1":"DA39A3EE5E6B4B0D3255BFEF95601890AFD80709","sha256":"E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855","file_type_category":"O","file_type_description":"empty","file_type_extension":"-","display_name":"C:\\testy.xml"},"data_id":"32fe182492834b6f88b1d95f6a14c886"}
First, you need to create a class (or multiple) that can represent the data you want to deserialize.
Looking at the input string you provided, you need a class for FileInfo, ScanDetail, ScanResults and one for the root (let's call it Scan).
It's simply a matter of mapping the JSON keys to a class property (and a dictionary for ScanDetail, since you probably don't want a property for each of it).
So, your classes should look like this:
public class Scan
public property file_id() as string
public property scan_results() AS ScanResults
public property file_info() as FileInfo
public property data_id() as string
End Class
public class ScanResults
public property scan_details As Dictionary(Of string, ScanDetail)
Public Property rescan_available() As Boolean
Public Property data_id() As String
Public Property scan_all_result_i() As Integer
Public Property start_time() As String
Public Property total_time() As Double
Public Property total_avs() As Integer
Public Property progress_percentage() As Integer
Public Property in_queue() As Integer
Public Property scan_all_result_a() As String
End Class
public class ScanDetail
public property scan_result_i() As integer
public property threat_found() as string
public property def_time() as string
public property scan_time() as string
End class
Public Class FileInfo
Public Property file_size() As Integer
Public Property upload_timestamp() As String
Public Property md5() As String
Public Property sha1() As String
Public Property sha256() As String
Public Property file_type_category() As String
Public Property file_type_description() As String
Public Property file_type_extension() As String
Public Property display_name() As String
End Class
Now the deserializing is as easy as
Dim details = NewtonSoft.JSon.JsonConvert.DeserializeObject(Of Scan)(your_json_string)
To get all threat_found values, you can easily query the result:
Dim threats = details.scan_results.scan_details.Select(Function(kvp) kvp.Value.threat_found) _
.Where(Function(t) Not String.IsNullOrWhiteSpace(t)) _
.ToList()
Here is how to deserialize that JSON string assuming you have referenced Json.Net. What you get is a dynamic object with property names the same as the JSON property names. If you were to create a Class with the correct properties you could also deserialize into that specific type and you would have the benefit of strong typing. Put a break point after this code and run with Debug. Look in the Locals window and you can inspect "theobj"'s properties.
Dim obj As String = "{""file_id"":""aaa60a443e3a4426944da9e6fe8a3f3c"",""scan_results"":{""scan_details"":{""AegisLab"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Agnitum"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Ahnlab"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-24T00:00:00Z"",""scan_time"":1.0},""Antiy"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""AVG"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Avira"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""BitDefender"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""ByteHero"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""ClamWin"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""CYREN"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""DrWebGateway"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Emsisoft"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""ESET"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Filseclab"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Fortinet"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""F-prot"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""F-secure"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""GFI"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Hauri"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Ikarus"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Jiangmin"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""K7"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-20T00:00:00Z"",""scan_time"":1.0},""Kaspersky"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Lavasoft"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""McAfee-Gateway"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Microsoft"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""NANO"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""nProtect"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Preventon"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""QuickHeal"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Sophos"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""STOPzilla"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-21T00:00:00Z"",""scan_time"":1.0},""SUPERAntiSpyware"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Symantec"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Tencent"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""TotalDefense"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""TrendMicro"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-21T00:00:00Z"",""scan_time"":1.0},""TrendMicroHouseCall"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-21T00:00:00Z"",""scan_time"":1.0},""VirIT"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-20T00:00:00Z"",""scan_time"":1.0},""VirusBlokAda"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-20T00:00:00Z"",""scan_time"":1.0},""Xvirus"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-23T00:00:00Z"",""scan_time"":1.0},""Zillya!"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-22T00:00:00Z"",""scan_time"":1.0},""Zoner"":{""scan_result_i"":0,""threat_found"":"""",""def_time"":""2015-02-18T00:00:00Z"",""scan_time"":1.0}},""rescan_available"":true,""data_id"":""32fe182492834b6f88b1d95f6a14c886"",""scan_all_result_i"":0,""start_time"":""2015-02-23T13:10:55.549Z"",""total_time"":1.0,""total_avs"":43,""progress_percentage"":100,""in_queue"":0,""scan_all_result_a"":""Clean""},""file_info"":{""file_size"":0,""upload_timestamp"":""2015-02-23T00:40:41.029Z"",""md5"":""D41D8CD98F00B204E9800998ECF8427E"",""sha1"":""DA39A3EE5E6B4B0D3255BFEF95601890AFD80709"",""sha256"":""E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"",""file_type_category"":""O"",""file_type_description"":""empty"",""file_type_extension"":""-"",""display_name"":""C:\\testy.xml""},""data_id"":""32fe182492834b6f88b1d95f6a14c886""}"
Dim theobj = JsonConvert.DeserializeObject(obj)
Thanks for your reply guys. I have done it by following code snippet
Dim jsonstring = IO.File.ReadAllText("C:\\Users\\Administrator\\Desktop\\json.txt")
Dim jo = Newtonsoft.Json.Linq.JObject.Parse(jsonstring)
Dim scanDetail = jo("scan_results")("scan_details")
Dim virusCount As Integer
virusCount = 0
For Each entry As Newtonsoft.Json.Linq.JProperty In scanDetail
entry.CreateReader()
Console.WriteLine(entry.Name)
For Each Val As Object In entry
Dim abc = Newtonsoft.Json.Linq.JObject.Parse(Val.ToString())
Dim threatFound As String = abc("threat_found")
Dim result As Integer = String.Compare(threatFound, "")
If result = -1 Then
virusCount = virusCount + 1
End If
Next
Next
If virusCount = 0 Then
Console.WriteLine("No Virus")
Else
Console.WriteLine("Virus")
End If

Parsing a file containing multiple JSON objects separated by blank lines or tabs

I am having trouble trying to get JSON parsed correctly here. I have the following format and tried using JObjects, but what it does is split one object into its different objects. Perhaps an example will make sense:
{
"completed_in": 0.012,
"max_id": 136536013832069120,
"max_id_str": "136536013832069120",
"next_page": "?page=2&max_id=136536013832069120&q=twitterapi&rpp=1",
"page": 1,
"query": "twitterapi",
"refresh_url": "?since_id=136536013832069120&q=twitterapi",
"results": [
{
"created_at": "Tue, 15 Nov 2011 20:08:17 +0000",
"from_user": "fakekurrik",
"from_user_id": 370773112,
"from_user_id_str": "370773112",
"from_user_name": "fakekurrik",
"geo": null,
"id": 136536013832069120,
"id_str": "136536013832069120",
"iso_language_code": "en",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http://a1.twimg.com/profile_images/1540298033/phatkicks_normal.jpg",
"source": "<a href="http://twitter.com/">web</a>",
"text": "#twitterapi, keep on keeping it real",
"to_user": "twitterapi",
"to_user_id": 6253282,
"to_user_id_str": "6253282",
"to_user_name": "Twitter API"
}
],
"results_per_page": 1,
"since_id": 0,
"since_id_str": "0"
}
This is what I consider one object. I have files that have hundreds of these and just separated by a tab or blank line. Now if I use JObject
Dim jobj As JObject = JObject.Parse(txtStuff.ToString())
Dim results As List(Of JToken) = jobj.Children().ToList
Results contains all the individual tokens. How can I get each object like the above (the entire object) into a list to process?
It sounds like you're really asking two questions here.
Given the above JSON, how do I get the data into a nice object structure?
Given that I have files containing lots of these objects, how do I get them into a list?
The first part is very easy. Just define a class structure that matches your JSON, then use JsonConvert.DeserializeObject() to deserialize the JSON into that object. For the JSON you posted, the class structure would look something like this:
Class RootObject
Public Property completed_in As Double
Public Property max_id As Long
Public Property max_id_str As String
Public Property next_page As String
Public Property page As Integer
Public Property query As String
Public Property refresh_url As String
Public Property results As List(Of Result)
Public Property results_per_page As Integer
Public Property since_id As Integer
Public Property since_id_str As String
End Class
Class Result
Public Property created_at As String
Public Property from_user As String
Public Property from_user_id As Integer
Public Property from_user_id_str As String
Public Property from_user_name As String
Public Property geo As Object
Public Property id As Long
Public Property id_str As String
Public Property iso_language_code As String
Public Property metadata As Metadata
Public Property profile_image_url As String
Public Property source As String
Public Property text As String
Public Property to_user As String
Public Property to_user_id As Integer
Public Property to_user_id_str As String
Public Property to_user_name As String
End Class
Class Metadata
Public Property result_type As String
End Class
You can deserialize it like this:
Dim obj As String = JsonConvert.DeserializeObject(Of RootObject)(json)
So at this point, obj will contain all the data from one object as you have defined it in your question. Now, you have indicated that you have a file that has many of these JSON objects together separated by a tab or a blank line. You can't just read the whole file in and give it to the JSON parser as one big string because this format isn't valid JSON. (Each individual object is valid JSON of course, but when strung together with tabs or blank line separators, the whole is not valid.) So, you will need to read the file in, line by line (or perhaps character by character) to find the separators and break it up into valid JSON objects that the parser can understand. Each time you find a separator, take all the data that you've read since the last separator and feed that to the deserializer. The result of each deserialization will be a valid RootObject which you can then add to a list as you go along.
Here is some code to give you an idea of how this might work. You may have to tweak it, depending on your needs, but I'm guessing it's not that far off the mark.
'' This function will read a file containing a series of JSON objects separated by
'' some string that is NOT part of the JSON. Could be a blank line or a tab or
'' something else. It will return a list of the deserialized JSON objects.
'' This function relies on two other helper functions (below).
Function ReadJsonFile(fileName As String, separator As String) As List(Of RootObject)
Dim objects As New List(Of RootObject)
Using sr As New StreamReader(fileName)
Dim json As String
Do
json = ReadToSeparator(sr, separator)
If json.Length > 0 Then
objects.Add(JsonConvert.DeserializeObject(Of RootObject)(json))
End If
Loop Until json.Length = 0
End Using
Return objects
End Function
'' This function will read and build up a string until the given separator is found.
'' Once the separator is found, it returns the string with the separator removed.
'' If no separator is found before the end of the data is reached, it returns
'' whatever was read to that point.
Function ReadToSeparator(reader As TextReader, separator As String) As String
Dim sb As New StringBuilder()
While reader.Peek <> -1
Dim ch As Char = ChrW(reader.Read())
sb.Append(ch)
If TailMatchesSeparator(sb, separator) Then
sb.Remove(sb.Length - separator.Length, separator.Length)
Exit While
End If
End While
Return sb.ToString()
End Function
'' This function checks whether the last characters in a StringBuffer match the
'' given separator string. Returns true if so or false if not.
Function TailMatchesSeparator(sb As StringBuilder, separator As String) As Boolean
If sb.Length >= separator.Length Then
Dim i As Integer = sb.Length - 1
For j As Integer = separator.Length - 1 To 0 Step -1
If sb(i) <> separator(j) Then
Return False
End If
i = i - 1
Next
Return True
End If
Return False
End Function
To use this, just call ReadJsonFile, passing a file name and a separator string. For example:
Dim separator As String = vbCrLf + vbCrLf
Dim objects As List(Of RootObject) = ReadJsonFile("json.txt", separator)