Get a value from JSON data - json

I have this Json data need to get the values on vb.net
{
"type": "push",
"targets": ["stream"],
"push": {
"type": "mirror",
"source_device_iden": "ujzp6Xr9A4asjyjskXPzu8",
"source_user_iden": "ujzp6Xr9A4a",
"client_version": 354,
"dismissible": true,
"icon": "ok",
"title": "test",
"body": "Hi",
"application_name": "WhatsApp",
"package_name": "com.whatsapp",
"notification_id": "1",
"notification_tag": "y9x5Q2YAI\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n",
"conversation_iden": "{\"package_name\":\"com.whatsapp\",\"tag\":\"y9x5Q2YAI\\\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\\n\",\"id\":1}"
}
}
I tried this code it is return error
Dim json As String = TextBox1.Text
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "push"
For Each msg As JObject In item.Value
Dim tyep As String = msg("type")
Dim source As String = msg("source_device_iden")
Next
End Select
Next
System.InvalidCastException: 'Unable to cast object of type
'Newtonsoft.Json.Linq.JProperty' to type
'Newtonsoft.Json.Linq.JObject'.'

Dim json As String = TextBox1.Text
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "push"
For Each msg As JObject In item
Dim tyep As String = msg("type")
Dim source As String = msg("source_device_iden")
Next
End Select
Next

Related

How to read Json array using vb.net?

I try to read json array which return from RestResponse using following code , i am used RestClient to call POST method
Dim clientPI As RestClient = New RestClient("https://sampleurl")
Dim requestPI = New RestRequest(Method.POST)
requestPI.AddParameter("name", "Aravind")
requestPI.AddParameter("username", "aravind")
requestPI.AddParameter("password", "aravind123")
requestPI.AddParameter("id", "100")
Dim responsePI As RestResponse = clientPI.Execute(requestPI)
Dim StrReturnPI As JValue = responsePI.Content.ToString
Dim serPI As JObject = JObject.Parse(StrReturnPI)
Dim dataPI As List(Of JToken) = serPI.Children().ToList
For Each item As JProperty In dataPI
item.CreateReader()
Select Case item.Name
Case "result"
output += "Document_id:" + vbCrLf
For Each comment As JObject In item.Values
Dim u As String = comment("Document_id")
output += u + vbTab
Next
Case "Inv_Date"
output += "Inv_Date:" + vbCrLf
For Each msgDate As JObject In item.Values
Dim f As String = msgDate ("value")
output += f + vbTab
Next
Case "Inv_Number"
output += "Inv_Number:" + vbCrLf
For Each msg As JObject In item.Values
Dim f As String = msg("value")
output += f + vbTab
Next
End Select
Next
Sample Json
{{
"result": [
{
"Document_id": "598dce483b97c",
"file_name": "2022-04-04_09_13_14.847228.pdf",
"Inv_Date": {
"value": "15-Jul-2019",
},
"Inv_Number": {
"value": "1920021347",
}
}
]],
"status": "complete"
}}
From above code i can read only value from Document_id and file_name but cant read value from Inv_Date and Inv_Number.
Anyone help will be appreciated.
Thanks and regards
Aravind
First of all, sorry because I can't check against a proper vb.net ide actually so some typo can occur, but I think this may solution your problem:
Get the values inside the result case as the structure is defined that way
Case "result"
output += "Document_id:" + vbCrLf
For Each comment As JObject In item.Values
Dim u As String = comment("Document_id")
output += u + vbTab
Dim invDate As JObject = comment("Inv_Date")
Dim invNumber As JObject = comment("Inv_Number")
Dim invDateValue As String = invDate("value")
output += invDateValue + vbTab
Dim invNumberValue As String = invNumber("value")
output += invNumberValue + vbTab
Next

Read JSON URL using Visual Basic .net

I'm trying to read URL containing JSON
Reading the file in the URL is ok, but when trying to parse the JSON I get an error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 2.
The code:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("http://phvarde.kundeside.dk/json?key=t6%$SVAKsG39"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As Object = JObject.Parse(rawresp)
TxtFornavn.Text = If(jResults("name") Is Nothing, "", jResults("name").ToString())
TxtAdresse.Text = If(jResults("address") Is Nothing, "", jResults("address").ToString())
You are getting this error because your JSON represents an array of objects, not just a single object. In this case you need to use JArray.Parse instead of JObject.Parse.
Dim array As JArray = JArray.Parse(json)
For Each item As JObject In array
Dim name As String = If(item("name") Is Nothing, "", item("name").ToString())
Dim address As String = If(item("address") Is Nothing, "", item("address").ToString())
// ... process name and address ...
Next
Fiddle: https://dotnetfiddle.net/2wfA17

json.parse allow null or missing

MY JSON String
{
"name": "username",
"status": "mystatus",
"place": {
"name": "placename",
}
My Code
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://myjsonstring.com/json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
if (rawresp != null)
name.Text = jResults("name").ToString()
status.Text = jResults("status").ToString()
placename.Text = jResults("place")("name").ToString()
End If
Catch ex As System.Net.WebException
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
my issue is sometimes my json may look like this
{
"name": "username",
"place": {
"name": "placename",
}
My JSON Explained
"name": "name here",
"items": {
"myitem": {
"icon": "myitem.jpg",
"myitem2": {
"icon": "myitem2.jpg",
}
My Code I Have Tried
myitem.Text = If(jResults2("items")("myitem")("icon") Is Nothing, "", jResults2("items")("myitem")("icon").ToString())
myitem2.Text = If(jResults2("items")("myitem2")("icon") Is Nothing, "", jResults2("items")("myitem2")("icon").ToString())
when the value is missing from myitem it stops the JSON and myitem2 never displays.
As this happens my project throws a null value exception, I have severely condensed my json string and code for readability but my question is there a way to handle the error when "status" is missing from the string and continue to parse the rest of the objects?
Or if its possible when this value is missing/null replace it with something else but if this route was chosen I would like to set a different value for each.
Check if jResults("status") and other properties are null (Nothing) before doing .ToString().
Dim jResults As JObject = JObject.Parse(rawresp)
name.Text = If(jResults("name") Is Nothing, "", jResults("name").ToString())
status.Text = If(jResults("status") Is Nothing, "", jResults("status").ToString())
placename.Text = If(jResults("place") Is Nothing, "", jResults("place")("name").ToString())

Newtonsoft.Json.JsonReaderException

I have a problem with Newtonsoft.Json. I'm trying to parse JSON from a URL but I'm getting an error. Here is the JSON:
[
{
"ID": "0",
"Nome": "we",
"Data": "2013-09-16",
"Orario": "00:00:16",
"Prestazione": "dfg",
"Stato": "dfg",
"Numero_Telefono": "dfg"
},
{
"ID": "0",
"Nome": "fg",
"Data": "2013-09-26",
"Orario": "00:00:00",
"Prestazione": "",
"Stato": "",
"Numero_Telefono": ""
},
{
"ID": "1",
"Nome": "davide",
"Data": "2013-09-26",
"Orario": "00:00:16",
"Prestazione": "ds",
"Stato": "sd",
"Numero_Telefono": "3546"
}
]
Here is the code I am using:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://nhd.altervista.org/connectDb.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JProperty In results
item.CreateReader()
MsgBox(item.Value("img")) ' because my tag in json is img
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
This is the error I receive when I try to parse the JSON:
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Can you help me solve this?
You are getting this error because you are using JObject.Parse, which expects a single JSON object, but your JSON contains an array. To correct this, use JArray.Parse instead.
But, there is another problem: the rest of your code is not set up to handle the results correctly. Because your results are an array of objects, your For Each loop needs to be expecting JObject items, not JProperty items. Once you have each item, you can then get the properties from them as needed.
I am not sure what you were trying to do with the item.CreateReader() line, as you are not doing anything with its return value, and you don't seem to need anyway. Similarly, I am also confused with your MsgBox(item.Value("img")) line, because there is no "img" property anywhere in the JSON. So this will always be null.
Here is some corrected code which will parse the JSON and display all the properties for each object in the results. This should give you a starting point to work with.
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://nhd.altervista.org/connectDb.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JArray = JArray.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JObject In results
Dim demo As String = ""
For Each prop As JProperty In item.Properties()
demo = demo + prop.Name + " = " + prop.Value.ToString() + vbCrLf
Next
MsgBox(demo)
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try

How to export Excel to JSON in specific format

I am using the following codes:
Private Sub CommandButton1_Click()
Dim excelRange As Range
Dim jsonItems As New Collection
Dim jsonDictionary As New Dictionary
Dim jsonFileObject As New FileSystemObject
Dim jsonFileExport As TextStream
Dim i As Long
Dim cell As Variant
Set excelRange = Sheet1.Cells(3, 3).CurrentRegion
For i = 4 To excelRange.Rows.Count
jsonDictionary("ID") = Sheet1.Cells(i, 1)
jsonDictionary("Pass") = Sheet1.Cells(i, 2)
jsonDictionary("MN") = Sheet1.Cells(i, 3)
jsonDictionary("Email") = Sheet1.Cells(i, 4)
jsonItems.Add jsonDictionary
Set jsonDictionary = Nothing
Next i
MsgBox (JsonConverter.ConvertToJson(jsonItems, Whitespace:=0))
Set jsonFileExport = jsonFileObject.CreateTextFile(Application.GetSaveAsFilename(fileFilter:="Text Files (*.json), *.json"), True)
jsonFileExport.WriteLine (JsonConverter.ConvertToJson(jsonItems, Whitespace:=3))
I got JSON file in following format:
[
{
"id": "AA2478FV",
"PAss": "MAAS",
"MN": "9878965421",
"email": "",Abc#123
}]
But I need JSON in the following format:
{"b2b deatils":[{"id":"01AF2578T","pass":"N","MN":8789755654,"furdetails":[{"nameorg":
[{"emp":1,"itm_det":{"recmount":0}}]}]
How can I get this ?