looping over items and access property of a parsed json object - json

OK i know how to parse using newtonsoft.
but I don't know how can i get every value of key inside parsed string
this is the json encoded string
{"result":[{"orderid":"94","imei":"clipper"},{"orderid":"93","item":"shoes"},{"orderid":"92","item":"bag"},{"orderid":"91","item":"shirt"}]}
Dim xreadingJson = Newtonsoft.Json.Linq.JObject.Parse(htmlcode)
Dim resultorder As String = xreadingJson.Item("result").ToString
then the result order is
[
{
"orderid": "94",
"item": "clipper"
},
{
"orderid": "93",
"item": "shoes"
},
{
"orderid": "92",
"item": "shoes"
},
{
"orderid": "91",
"item": "bag"
}
]
On looping how can I get the value of orderid and item.
thank you
Update:
I resolved it using this code
Dim o As JObject = JObject.Parse(htmlcode)
Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
item.CreateReader()
'MsgBox(item.Value)
If item.Value.Type = JTokenType.Array Then
For Each subitem As JObject In item.Values
MsgBox(subitem("orderid"))
MsgBox(subitem("item"))
Next
End If
Next

I believe Newtonsoft's JObject has a JObject.GetValue("property_name") method

Related

Loop the contents of a JSON array object

I am new to Vb.net. Having a JSON string as given below, I tries to deserialize the JSON into an Object using JsonConvert.DeserializeObject().
I am trying to loop values inside the Content object in the given JSON to fetch its values.
I tried using a for loop, but I'm not able to get the exact values.
Dim result As String = {
"status": "0001",
"Result": {
"IsError": "0",
"Data": {
"Type": "a",
"Header": [
"v1",
"v2",
"v3",
"v4",
"v5"
],
"Content": [
[
"001",
"Raj",
"1",
"N",
""
],
[
"002",
"Vignesh",
"1",
"N",
""
],
[
"778",
"Ramesh",
"1",
"N",
""
],
[
"792",
"Suresh",
"1",
"N",
""
],
[
"703",
"Karthick",
"1",
"N",
""
],
[
"1247",
"Ram",
"1",
"N",
""
]
]
}
}
}
Dim jsonResult2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(result)
If you just want to deserialize the Content array, you can parse the JSON with JToken.Parse(), then deserialize to a List(Of String()) that section only.
Dim jsonResult = JToken.Parse(result)
Dim content = JsonConvert.DeserializeObject(Of List(Of String()))(
jsonResult("Result")("Data")("Content").ToString()
)
Or, you could use a class Model to deserialize the whole JSON, then access each object as a standard .Net Property value.
Public Class StatusResultsRoot
<JsonProperty("status")>
Public Property Status As String
Public Property Result As Result
End Class
Public Partial Class Result
Public Property IsError As String
Public Property Data As Data
End Class
Public Partial Class Data
<JsonProperty("Type")>
Public Property DataType As String
Public Property Header As List(Of String)
Public Property Content As List(Of String())
End Class
'[...]
Dim statusResult = JsonConvert.DeserializeObject(Of StatusResultsRoot)(result)
The Content List is then
Dim content As List(Of String()) = statusResult.Result.Data.Content
' Loop the List of String(), print the combined array of strings
For Each stringArray As String() In content
Console.WriteLine(String.Join(", ", stringArray))
Next
In case you actually want to embed a JSON as a string, you can use an XML element literal, defining an XElement by enclosing the JSON with <node> ... </node> markers.
You can then paste in the JSON as is (no need to double the double-quotes).
The JSON is then the string representation of the first node of the XElement: i.e., [XElement].FirstNode.ToString(). For example:
Dim xResult = <json> {
"status": "0001",
"Result": {
"IsError": "0",
"Data": {
' [... other content ...]
}
}
} </json>
Dim json As String = xResult.FirstNode.ToString()
You cannot do this in C#.
A string in VB must begin and end with a ".
The inner double quotes should be replaced with "".
So a proper string(when assigning it in code) would look like:
Dim result as string = "{
""status"": ""0001"",
...
}
"

issue with Retrieve original value from json

New Help to retrieve original value from Json row Data the below code strip some "\"
-------------Json data-----------------
{
"type": "push",
"targets": ["stream"],
"push": {
"type": "mirror",
"source_device_iden": "ujzp6Xr9A4asjyjskXPzu8",
"source_user_iden": "ujzp6Xr9A4a",
"client_version": 354,
"dismissible": true,
"icon": "test",
"title": "ok",
"body": "Hi",
"application_name": "android",
"package_name": "com.android",
"notification_id": "1",
"notification_tag": "y9x5Q2YAI\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n",
"conversation_iden": "{\"package_name\":\"com.android\",\"tag\":\"y9x5Q2YAI\\\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\\n\",\"id\":1}"
}
}
-------------------- VB code ---------------------------
Private Sub jsonData(JsonStr As String)
Dim json As String = JsonStr
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim Result as string
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "push"
For Each msg As JObject In item
Result = msg("conversation_iden")
Next
End Select
Next
End Sub
--------------------------- resulet -----------------------------
Result = "{"package_name":"com.com.android","tag":"y9x5Q2YAI/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n","id":1}"
original value :
"{\"package_name\":\"com.android\",\"tag\":\"y9x5Q2YAI\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n\",\"id\":1}"

How do I loop/iterate through this deserialized object using Newtonsoft Json.net?

I have the following JSON object:-
Public Class oPartner
Public Property PartnerID() As String
Public Property PartnerTitle() As String
Public Property PartnerStrapline() As String
Public Property PartnerData() As String
End Class
And the following partners.json JSON file:-
[
{
"PartnerID": "1",
"PartnerTitle": "TITLE1",
"PartnerStrapline": "STRAP1",
"PartnerData": "SOME INFO IN HERE",
"PartnerImage": ""
},
{
"PartnerID": "2",
"PartnerTitle": "TITLE2",
"PartnerStrapline": "STRAP2",
"PartnerData": "SOME MORE INFO IN HERE",
"PartnerImage": ""
},
{
"PartnerID": "3",
"PartnerTitle": "TITLE3",
"PartnerStrapline": "STRAP3",
"PartnerData": "MORE INFO",
"PartnerImage": ""
}
]
So I can read the JSON and deserialize using:-
Dim data As oPartner = JsonConvert.DeserializeObject(Of oPartner)(File.ReadAllText("c:\partners.json"))
But I can't work out how I would loop through the json in vb (or C#)?
Your JSON represents an array of objects, but you are trying to deserialize it into a single instance. You need to deserialize into an array (or List) of oPartner instead. Try it like this:
Dim data As List(Of oPartner) = JsonConvert.DeserializeObject(Of List(Of oPartner))(File.ReadAllText("c:\partners.json"))
Then you can loop through the list like this:
For Each partner As oPartner In data
Console.WriteLine(partner.PartnerID)
Console.WriteLine(partner.PartnerTitle)
Console.WriteLine(partner.PartnerStrapline)
Console.WriteLine(partner.PartnerData)
Console.WriteLine()
Next
Fiddle: https://dotnetfiddle.net/N8Im6q

vb.net get values from json like string in DataTable

Here is my json like string:
{
"ProductGroupId": "3",
"ProductGroupName": "Frisdranken",
"ProductId": "139",
"ProductName": "Cola",
"Quantity": 1,
"QuantityUnit": "P",
"SellingPrice": 2.7,
"VatRateId": "A",
"DiscountLines": []
}, {
"ProductGroupId": "3",
"ProductGroupName": "Frisdranken",
"ProductId": "146",
"ProductName": "Plat water",
"Quantity": 1,
"QuantityUnit": "P",
"SellingPrice": 2.6,
"VatRateId": "A",
"DiscountLines": []
}
How do I get the "ProductName" and "Quantity" in a datatable?
Assuming your json is an array and you just missed the enclosing [...], you can:
Dim json As String = "[{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""139"",""ProductName"":""Cola"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.7,""VatRateId"":""A"",""DiscountLines"":[]},{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""146"",""ProductName"":""Plat water"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.6,""VatRateId"":""A"",""DiscountLines"":[]}]"
'Use JSON.Net to obtain a JArray
Dim jobj As JArray = JsonConvert.DeserializeObject(json)
'Extract just the fields you want from the data with a Linq projection into
'anonymous type with ProductName and Quantity fields
Dim ProductsAndQuantities = jobj.Select(Function(j)
Return New With {
.ProductName = j("ProductName"),
.Quantity = j("Quantity")}
End Function)
'build your DataTable
Dim dt As DataTable = New DataTable()
dt.Columns.Add("ProductName")
dt.Columns.Add("Quantity")
'Load the data table
For Each item In ProductsAndQuantities
Dim dr As DataRow = dt.NewRow()
dr("ProductName") = item.ProductName
dr("Quantity") = item.Quantity
dt.Rows.Add(dr)
Next

VB.NET need help in deserialization of a JSON

Hey I need help in deserializing this:
{
"success": true,
"rgInventory": {
"2722309060": {
"id": "2722309060",
"classid": "939801430",
"instanceid": "188530139",
"amount": "1",
"pos": 1
},
"2722173409": {
"id": "2722173409",
"classid": "937254203",
"instanceid": "188530139",
"amount": "1",
"pos": 2
},
"2721759518": {
"id": "2721759518",
"classid": "720293857",
"instanceid": "188530139",
"amount": "1",
"pos": 3
},
"2721748390": {
"id": "2721748390",
"classid": "310777652",
"instanceid": "480085569",
"amount": "1",
"pos": 4
}
}
}
at the end it should look like:
2722309060#2722173409#2721759518#2721748390
Dim result = JsonConvert.DeserializeObject(jsonstring) 'deserialize it
Dim tempfo As String = result("rgInventory").ToString 'get rgInventory
Console.WriteLine(tempfo)
how i can deserialize all 'id's?
The json contains a Dictionary of items, the IDs you want are the keys. If you deserialized it, you could get them from the Dictionary. Otherwise, you can use JParse and linq to get them:
Dim jstr As String = ...
' parse the json
Dim js As JObject = JObject.Parse(jstr)
' extract the inventory items
Dim ji As JObject = JObject.Parse(js("rgInventory").ToString)
' get and store the keys
Dim theIds As List(Of String) = ji.Properties.Select(Function(k) k.Name).ToList()
I suspect that when "success" is false that the resulting items list will be empty. Test that it works:
For Each s As String In theIds
Console.WriteLine(s)
Next
Result:
2722309060
2722173409
2721759518
2721748390