How can I post a JSON object using a Dictionary? - json

Here is the JSON content that needs to be posted.
{
"getcart": {
"version": "1.0",
"account": "6566",
"username": "112",
"password": "xxxxxxxx",
"cartid": "57044d79",
} }
Code:
Dim jsonPost As New JsonPost("https://www.example.aspx")
Dim dictData As New Dictionary(Of String, Object)
dictData.Add("version", "1.0")
dictData.Add("account", "6566")
dictData.Add("username", "112")
dictData.Add("password", "xxxxxxxx")
dictData.Add("cartid", "57044d79")
Dim json As JObject = JObject.Parse(JsonPost.postData(dictData))
Dim response As String = JsonPost.postData(dictData)
MsgBox(response)
The error I'm getting:
Error reading JObject from JsonReader. Path'',line 0 postion 0
How can I fix this?

I couldn't do it using the dictionary. But I was able to post it as a string.
The main issue was declaring a JSON string that contains an object in Visual Basic. Here is how I did it:
Dim JsonData As String = "{'getcart':{
'version':'1.0',
'account':'6566',
'username':'112',
'password':'xxxxxxxx',
'cartid':'57044d79',
}}"
Dim Uri As String = "https://www."
Dim data = Encoding.UTF8.GetBytes(JsonData)
Dim result_post = SendRequest(New Uri(Uri), data, "application/json", "POST")
MsgBox(result_post)
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function

Related

VB .NET JSON Deserialization

I'm having a problem with JSON deserialization hope you can help me.
I have a JSON that have the following information:
{
"object":"list",
"more":false,
"data":[
{
"object":"number",
"id":"1",
"code":"1",
"name":"One",
},
{
"object":"number",
"id":"2",
"code":"2",
"name":"Two",
}
...
So I've a created a simple app so I can use that information:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim uri As New Uri(uriString)
'Make Request
Dim Request As HttpWebRequest = HttpWebRequest.Create(uri)
Request.Method = "GET"
'Get Response
Dim Response As HttpWebResponse = Request.GetResponse()
'Read Response
Dim Read = New StreamReader(Response.GetResponseStream())
Dim Raw As String = Read.ReadToEnd()
'Convert response
Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(Raw)
For Each item In dict
MsgBox(item)
MsgBox(item("code"))
TextBox1.Text += item("code").ToString + " - " + item("name").ToString + vbNewLine
Next
End Sub
It seems I get the response, since the Read I get the JSON, but after that, I can't get the information listed in that JSON. What I'm doing wrong?
You are not de-serializing properly. Your dict is empty like that.
This will work as intended.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim Request As HttpWebRequest = WebRequest.Create(New Uri(uriString))
Dim JSON_Response As String = New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd()
Dim JSON_Obj1 As Object = New JavaScriptSerializer().DeserializeObject(JSON_Response)
Dim Test1 as String = JSON_Obj1("data")(0)("code")
For Each item In JSON_Obj1("data")
Debug.Print(item("code"))
Next
End Sub

How to pass a complex JSON object through VB.net to call Rest API

I have a Rest API which I have to call from my vb.net code.
In the Postman I pass the arguments in the Body as follows:
{
"Search" :
{
"EmpName" : "Rachel",
"EmpID" : "1100320"
},
"IncludeAttributes" : ["EmpId", "EmpName","Department","Salary","ManagerId"]
}
My problem is that I am not sure how can I pass this kind of parameter through my call from VB.Net call.
Here is what I have tried:
Dim searchParameters = New Dictionary(Of String, String)()
searchParameters.Add("EmpName", "Rachel")
searchParameters.Add("EmpID", "1100320")
Dim jsonSearchParameters =
JsonConvert.SerializeObject(searchParameters)
Dim stringContent = New StringContent(jsonSearchParameters, Encoding.UTF8, "application/json")
And now I am clueless of how to pass IncludeAttributes part in the same object.
Any help please?
As #cricket_007 suggests a Dictionary(Of String, Object) would work:
Dim search = New Dictionary(Of String, String) From {
{"EmpName", "Rachel"},
{"EmpID", "1100320"}
}
Dim searchParameters = New Dictionary(Of String, Object) From {
{"Search", search},
{"IncludeAttributes", New String() {"EmpId", "EmpName", "Department", "Salary", "ManagerId"}}
}
Dim jsonSearchParameters = JsonConvert.SerializeObject(searchParameters)
Dim stringContent = New StringContent(jsonSearchParameters, Encoding.UTF8, "application/json")
Alternatively, create a class to hold the parameters:
Public Class Search
Public Property EmpName As String
Public Property EmpID As String
End Class
Public Class SearchParameters
Public Property Search As Search
Public Property IncludeAttributes As String()
End Class
and then fill the classes in with the appropriate data:
Dim search = New Search With
{
.EmpName = "Rachel",
.EmpID = "1100320"
}
Dim searchParameters = New SearchParameters With
{
.Search = search,
.IncludeAttributes = New String() {"EmpId", "EmpName", "Department", "Salary", "ManagerId"}
}
Dim jsonSearchParameters = JsonConvert.SerializeObject(searchParameters)
Dim stringContent = New StringContent(jsonSearchParameters, Encoding.UTF8, "application/json")
As cricket_007 suggested I tried Dictionary of string, object and it worked like a charm. For any one else coming here with the similar issue here is my piece of code, which worked:
Dim searchParameters = New Dictionary(Of String, String)()
searchParameters.Add("EmpId", EmpId)
searchParameters.Add("EmpName", "Rachel")
Dim includeAttributes() As String = {"EmpId", "Name", "Dept", "Manager", "Salary"}
Dim SearchAttributes As New Dictionary(Of String, Object)
SearchAttributes.Add("Search", searchParameters)
SearchAttributes.Add("IncludeAttributes", includeAttributes)
Dim jsonSearchParameters = JsonConvert.SerializeObject(SearchAttributes)

how to filter a specific part of a json string

ive been working on json for about 2 days and its all new to me so im learning as i go i have this string im working with
{
"elements": [{
"id": "123",
"hidden": false,
"name": "testname",
"sku": "1234",
"price": 2499,
"priceType": "FIXED",
"defaultTaxRates": true,
"cost": 1299,
"isRevenue": true,
"stockCount": 0,
"itemStock": {
"item": {
"id": "123"
},
"stockCount": 3,
"quantity": 3.0
},
"modifiedTime": 1504112254000
}],
"href": "http://api.server.com/items"
}
i am usnig the Newtonsoft.Json library
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Net
Imports System.IO
Public Class Form1
Dim token = ""
Dim url = "https://api.Server.com/"
Dim mid = ""
Dim parm1 = ""
Dim parm2 = ""
Dim parm3 = ""
Dim parm = parm1 & parm2 & parm3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim jsonURL As String = url & mid & "/items?" & parm
Dim reader As StreamReader
Dim errorMsg As String = Nothing
Try
Dim request As HttpWebRequest = CType(WebRequest.Create(jsonURL), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " + token)
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim jsonStr As String = reader.ReadToEnd()
Dim JsonObject As JObject = JObject.Parse(jsonStr)
Dim jsonArray As JArray = JArray.Parse(JsonObject.SelectToken("elements").ToString)
For Each items As JObject In jsonArray
Dim product As item = JsonConvert.DeserializeObject(Of item)(items.ToString)
idTxtbox.Text = product.id
hiddenTxtbox.Text = product.hidden
nameTxtbox.Text = product.name
skuTxtbox.Text = product.sku
priceTxtbox.Text = product.price
priceTypeTxtbox.Text = product.priceType
defaultTaxRatesTxtbox.Text = product.defaultTaxRates
CostTxtbox.Text = product.cost
isRevenueTxtbox.Text = product.isRevenue
stockCountTxtbox.Text = product.stockCount
For Each itema In product.itemStock
ListBox1.Items.Add(itema("itemStock"))
Next
modifiedTimeTxtbox.Text = product.modifiedTime
MsgBox("")
Next
Catch ex As WebException
errorMsg = "Download failed. The response from the server was: " +
CType(ex.Response, HttpWebResponse).StatusDescription
Console.WriteLine("Error: " + errorMsg)
End Try
End Sub
End Class
Class item
Public id As String
Public hidden As String
Public name As String
Public sku As String
Public price As String
Public priceType As String
Public defaultTaxRates As String
Public cost As String
Public isRevenue As String
Public stockCount As String
'Public itemStock As Dictionary(Of String, String) = New Dictionary(Of String, String)
'Public itemStock As List(Of String) = New List(Of String)
Public Property itemStock() As IList(Of String)
Get
Return m_itemStock
End Get
Set(ByVal value As IList(Of String))
m_itemStock = value
End Set
End Property
Private m_itemStock As IList(Of String)
Public modifiedTime As String
End Class
i can get all the values of the first group of data but cant seems the "stockCount": 3 to show up any idea how i can phrase this?
sorry if im not super clear if you need more info i will try to provide it
i have updated the code of what i have so far i have gotten the JsonConvert.DeserializeObject to work but still cant seem to get the values of
"itemStock": {
"item": {
"id": "123"
},
"stockCount": 3,
"quantity": 3.0
},
to populate in listbox1.items
i receive this error
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.IList`1[System.String]' because
the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be

vb.net Json Error converting value to type

I'm newbie in JSON, I made a first try with a file and it works fine. But my second file gives me headache.
The problem is that the second file start with this : [
my first file was like this
{
"GC": {
"Parameters": {
"feed": "gc",
"lang_code": "fr",
"fmt": "json",
} .................
I try many different things and I always have an error. The error is :
Additional information: Error converting value "person" to type 'JSonPerson'. Path '[0]', line 1, position 9.
Here's the second JSON file text (that start with the bracket "[" :
["person",
[{
"id": "19023",
"player_id": "16493",
"coach_id": "0",
"manager_id": "",
"official_id": ""
},
{
"id": "19024",
"player_id": "16494",
"coach_id": "1",
"manager_id": "",
"official_id": ""
}]]
Now my class:
Public Class JSonPerson
Public person As List(Of JSon_PersonDetail)
End Class
Public Class JSon_PersonDetail
Public id As String
Public player_id As String
Public coach_id As String
Public manager_id As String
Public official_id As String
Public user_id As String
Public first_name As String
Public last_name As String
End Class
And my code (that is the same for the first file, works perfect, but not with the second file):
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("c:\Global_files\person.json")
Dim reader2 As New StreamReader(stream)
Dim jsonData As String = reader2.ReadToEnd
Dim obj As List(Of JSonPerson)
obj = JsonConvert.DeserializeObject(Of List(Of JSonPerson))(jsonData)
I try this too:
Dim obj As JSonPerson
obj = JsonConvert.DeserializeObject(Of JSonPerson)(jsonData)
But I'm not able to push data inside my class I have errors:
Does someone know what's my problem ?
Update
I also tried reading directly from the stream using a JsonTextReader, like so:
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("c:Global_files\person.json")
Dim reader2 As New StreamReader(stream)
Dim jsonData As String = reader2.ReadToEnd
Dim reader As New JsonTextReader(reader2)
Dim people As JSonPeople
people = JsonSerializer.CreateDefault().Deserialize(Of JSonPeople)(reader)
reader2 have data. After the variable "reader" is empty. So the people is empty.
Here's the way I did it:
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("c:\Global_files\person.json")
Dim reader2 As New StreamReader(stream)
Dim jsonData As String = reader2.ReadToEnd
Dim jResults As JArray = JArray.Parse(jsonData)
'Here I know that is the children #1 that I need
Dim Data As List(Of JToken) = jResults.Item(1).Children().ToList
Dim vListOfPerson As New List(Of JSon_PersonDetail)
For Each item In Data
Dim ItemArray As Array = item.ToArray
Dim person As New JSon_PersonDetail
For Each element In ItemArray
Select Case element.name
Case "id"
person.id = element.value
Case "player_id"
person.player_id = element.value
Case "coach_id"
person.coach_id = element.value
Case "manager_id"
person.manager_id = element.value
Case "official_id"
person.official_id = element.value
Case "user_id"
person.user_id = element.value
Case "first_name"
person.first_name = element.value
Case "last_name"
person.last_name = element.value
End Select
Next
vListOfPerson.Add(person)
Next

How to parse json and read in vb.net

I have this code in my project:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = rawresp
and TextBox2 gets the JSON code correctly.
and this is my JSON code example:
{
"id":174543706,
"first_name":"Hamed",
"last_name":"Ap",
"username":"hamed_ap",
"type":"private"
}
My question:
How to get 174543706 from JSON code ("id") into TextBox3.Text???
You could use JavaScriptSerializer which is in System.Web.Script.Serialization.
Imports System.Web.Script.Serialization
Module Module1
Sub Main()
Dim s As String
Try
Dim rawresp As String = "{""id"":174543706,""first_name"":""Hamed"",""last_name"":""Ap"",""username"":""hamed_ap"",""type"":""private""}"
Dim jss As New JavaScriptSerializer()
Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)
s = dict("id")
Catch ex As Exception
End Try
End Sub
End Module
try this code :
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
Dim firstItem = jsonResulttodict.item ("id")
hope it help you !!
How to get 174543706 from JSON code ("id") into TextBox3.Text?
{
"id": 174543706,
"first_name": "Hamed",
"last_name": "Ap",
"username": "hamed_ap",
"type": "private"
}
Sorry if my reply was late. I hope my answer can help someone who's still confused.
So what you do was get the response and read the JSON.
After you do ReadToEnd():
Dim xr As XmlReader = XmlReader.Create(New StringReader(rawresp))
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(rawresp)
Then What you need to do is to read the data from the response. you do like this:
Dim res As String = JsonConvert.SerializeXmlNode(doc)
Dim ThisToken As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(res)
Dim response As String = ThisToken("response").ToString()
Dim ThisData As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(response)
After that yo can get the data from the response and convert it into string
Dim idx As String = ThisData("id").ToString()
// the value of idx will be: 174543706
Then last you can put it into Texbox3.Text.
JSON can be parsed using adding Newtonsoft.Json.dll reference
Code :
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim json As String = New System.Net.WebClient().DownloadString("http://time.jsontest.com/")
Dim parsejson As JObject = JObject.Parse(json)
Dim thedate = parsejson.SelectToken("date").ToString()
txt1.Text = "Date Is "+thedate
End Sub
End Class
Reference : Narendra Dwivedi - Parse JSON
This works:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = JObject.Parse(rawresp)("id")