Convert Json to dataset - json

DLL used: Newtonsoft.Json.Linq
When I convert another jason using below converter code it is working fine. but when i am converting given below jason getting error "{"Cannot add a nested relation or an element column to a table containing a SimpleContent column."}". If I replace the 1st seat to seat1 than it is working fine. But I cannot change anything on JSON as this response is shared by 3rd party operator.
Note : I cannot change anything on JSON.
Code:
Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
Dim xmlDoc As New XmlDocument
Dim objDS As DataSet
xmlDoc = CType(JsonConvert.DeserializeXmlNode("{""DT"": {" & jsonString.Trim().TrimStart("{").TrimEnd("}") & "} }"), XmlDocument)
objDS = New DataSet()
objDS.ReadXml(New XmlNodeReader(xmlDoc))
JSON:
{
"status":"success",
"msg":"",
"data":{
"block_key":"76570415041123",
"block_time":"7",
"ticket_detail":{
"msrtc":{
"reservation_charge":"5.0",
"asn_amount":"1.0",
"ac_service_charges":"0.0"
},
"upsrtc":"NA",
"hrtc":"NA",
"rsrtc":"NA"
},
"total_fare":280,
"base_fare":274,
"operator_commission_rate":"4.45",
"agent_commission_rate":"85",
"commission_without_gst":8.78,
"agent_tds_value":0.44,
"agent_net_commission":8.34,
"transaction_amount":271.66,
"test":{
"testing":{
"tripchild_con":"Y",
"post_passanger":[
{
"title":"Mr",
"name":"Ram",
"age":"70",
"sex":"M",
"birth":"0",
"seat_no":"45",
"subtotal":"280.0",
"total":"280",
"is_ladies":"false",
"mobile":"9579597539",
"email":"ram#gmail.com",
"id_type":null,
"id_number":null,
"name_on_id":null,
"primary":"True",
"ac":"false",
"sleeper":"false"
}
],
"value":{
"title":"Mr",
"name":"Ram",
"age":"70",
"sex":"M",
"birth":"0",
"seat_no":"45",
"subtotal":"280.0",
"total":"280",
"is_ladies":"false",
"mobile":"9579597539",
"email":"ram#gmail.com",
"id_type":null,
"id_number":null,
"name_on_id":null,
"primary":"True",
"ac":"false",
"sleeper":"false"
},
"senior_citizen_flag":"0",
"seats":{
"seats":[
"2",
"5",
"6",
"9",
"10",
"13",
"14",
"15",
"16",
"17",
"18",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"31",
"32",
"33",
"34",
"35",
"37",
"38",
"39",
"40",
"41",
"42",
"45"
],
"service_id":"724351",
"fare":"280.0",
"childFare":"145.0",
"seniorcitizenfare":"145.0"
},
"passengerDetails":"seniorfare else casse",
"adultFare seniorfare else casse":"274.0",
"tickets_total_basic_fare":274,
"adultFare":null
}
}
}
}

I think that Json structure cannot create Dataset.
So you have to process the data yourself and create it.
see source below
Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
Dim dto As TestDTO
dto = JsonConvert.DeserializeObject(Of TestDTO)(jsonString)
MsgBox(dto.status)
Class TestDTO
Property status As String
Property msg As String
Property data As dataDTO
End Class
Class dataDTO
Property block_key As String
Property ticket_detail As ticketdetailDTO
End Class
Class ticketdetailDTO
Property reservation_charge As String
End Class

Related

How to retrieve data from Json file into Winform with Json.Net

I am still fairly unfamiliar with Json, but I am trying to import data from a Json file into form fields of a Winform. For this I want to use Json.NET. I found the following example at https://www.codeproject.com/Articles/1201466/Working-with-JSON-in-Csharp-VB.
I have processed the code in my own form, but I cannot get the Json data into a form field.
My Json file has the following format:
{
"DataSource": {
"Id": "b94809c324ee4ab5b7dfa81e00b1e535",
"Name": "DataSourceName",
"Headers": [{
"Name": "ID",
"DisplayAt": "None"
}, {
"Name": "Datum storing",
"DisplayAt": "Title"
}, {
"Name": "Tijdstip melding",
"DisplayAt": "None"
}, {
"Name": "Projectnummer",
"DisplayAt": "None"
}, {
"Name": "Projectnaam",
"DisplayAt": "None"
}, {
"Name": "Servicemonteur",
"DisplayAt": "None"
}, {
"Name": "Start reistijd",
"DisplayAt": "None"
}, {
"Name": "starttijd werkzaamheden",
"DisplayAt": "None"
}, {
"Name": "eindtijd werkzaamheden",
"DisplayAt": "None"
}, {
"Name": "eind reistijd",
"DisplayAt": "None"
}, {
"Name": "omschrijving storing",
"DisplayAt": "None"
}, {
"Name": "oorzaak storing",
"DisplayAt": "None"
}, {
"Name": "omschrijving werkzaamheden",
"DisplayAt": "None"
}, {
"Name": "aanbevelingen",
"DisplayAt": "None"
}, {
"Name": "verbruikte materialen",
"DisplayAt": "None"
}, {
"Name": "zoekstring",
"DisplayAt": "None"
}, {
"Name": "categorie_ID",
"DisplayAt": "None"
}, {
"Name": "melding_van",
"DisplayAt": "None"
}],
"Rows": [
["valueId", "2018-02-26", "13:41:00", "104", "ProjectName1", "Engineer1, Engineer2", "11:00:00", "11:30:00", "12:45:00", "13:15:00", "Omschrijving", "Onbekend", "Omschrijving 2.", "Omschrijving 3.", null, "Omschrijving 4", "1", null],
["valueId", "2018-03-24", "13:41:00", "104", "ProjectName2", "Engineer1, Engineer2", "11:00:00", "11:30:00", "12:45:00", "13:15:00", "Omschrijving", "Onbekend", "Omschrijving 2.", "Omschrijving 3.", null, "Omschrijving 4", "1", null],
["valueId", "2018-03-12", "18:06:00", "173", "ProjectName3", "Engineer1, Engineer2", "11:00:00", "11:30:00", "12:45:00", "13:15:00", "Omschrijving", "Onbekend", "Omschrijving 2.", "Omschrijving 3.", null, "Omschrijving 4", "1", null]
],
"TotalRows": 3,
"LastUpdated": "2020-06-19T13:15:17.7400000Z",
"CompanyId": 12345
}
}
From this file I want to get the data from the Headers and the Rows. I started with retrieving the Headers from the file. So I made the following Class via jsonutils.com:
Imports Newtonsoft.Json
Namespace Models
Public Class Header
<JsonProperty("Name")>
Public Property Name As String
<JsonProperty("DisplayAt")>
Public Property DisplayAt As String
End Class
Public Class DataSource
<JsonProperty("Id")>
Public Property Id As String
<JsonProperty("Name")>
Public Property Name As String
<JsonProperty("Headers")>
Public Property Headers As Header()
<JsonProperty("Rows")>
Public Property Rows As String()()
<JsonProperty("TotalRows")>
Public Property TotalRows As Integer
<JsonProperty("LastUpdated")>
Public Property LastUpdated As DateTime
<JsonProperty("CompanyId")>
Public Property CompanyId As Integer
End Class
Public Class Category
<JsonProperty("DataSource")>
Public Property DataSource As DataSource
End Class
End Namespace
With the following code I want to get the values of the DataSource Class:
Private Sub GetData()
' Retrieve JSON data from file
Dim rawJson = File.ReadAllText(Path.Combine(filePath, fileName))
' Convert to C# Class typed object
Result = JsonHelper.ToClass(Of DataSource)(rawJson)
UpdateUI()
End Sub
At this point the Json File is loaded into rawJson and is going to be deserialized via the following function:
Public Function ToClass(Of T)(data As String, Optional jsonSettings As JsonSerializerSettings = Nothing) As T
Dim response = Nothing
If Not String.IsNullOrEmpty(data) Then
response = If(jsonSettings Is Nothing,
JsonConvert.DeserializeObject(Of T)(data),
JsonConvert.DeserializeObject(Of T)(data, jsonSettings))
End If
Return response
End Function
Only the result (response) of the function stays empty, but I can't figure out why. What I want is to retrieve the data from the Headers and the Rows and fill them in my form.

Read Json array vb.net

I'm getting mad about this.
I'm very new to Json.
I need to read the array ("items") from the json example provided.
I can read all other objets like "id","title","description"...but not the array of items.
Using Newtonsoft.Jason
Code (vb.net) : >>
Dim json As String = File.ReadAllText("C:\Test\Json\test.json")
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 item.Name
Case "results"
For Each comment As JObject In item.Values
txtConsole.Text = comment
Console.WriteLine(comment("id"))
Console.WriteLine(comment("title"))
Console.WriteLine(comment("description"))
Console.WriteLine(comment("tipe"))
Console.WriteLine(comment("author")("description"))
Console.WriteLine(comment("details")("conditions"))
'for each item in array
'Read the array of "products": here
'Console.WriteLine(comment("name")
'Console.WriteLine(comment("codeBar")
'next
Console.WriteLine(comment("details")("benefits"))
Console.WriteLine(comment("details")("price"))
Console.WriteLine(comment("details")("discount"))
Console.WriteLine(comment("details")("pays"))
Console.WriteLine(comment("datefrom"))
Console.WriteLine(comment("dateto"))
Next
End Select
Next
Json file >>
{
"total": 1,
"results": [
{
"id": 208,
"title": "This is the title",
"description": "This is the descripcion",
"tipe": "This is type",
"author": {
"descripcion": "description of author"
},
"details": {
"conditions": {
"items": [
{
"quantity": 6,
"products": [
{
"name": "Product one",
"codeBar": "7891000100103"
},
{
"name": "Product two",
"codeBar": "7894900061604"
},
{
"name": "Product three",
"codeBar": "7894900010015"
},
{
"name": "Product four",
"codeBar": "7894900092011"
}
]
}
]
},
"benefits": null,
"price": null,
"discount": null,
"pays": 5
},
"datefrom": "2015-08-06T00:00:00.000-0300",
"dateto": "2016-12-31T23:59:59.000-0200"
}
]
}
Desire Console output >>
208
This is the title
This is the descripcion
This is type
items
quantity: 6
products
"name": "Product one",
"codeBar": "7891000100103"
"name": "Product two",
"codeBar": "7894900061604"
"name": "Product three",
"codeBar": "7894900010015"
"name": "Product four",
"codeBar": "7894900092011"
5
06/08/2015 00:00:00
31/12/2016 22:59:59
Please, help me...thank u very much in advance !!
This might point you in the right direction. I was able to access the products array this way:
' Open the file using a stream reader.
Dim sr As New StreamReader(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\json.txt")
Dim line As String
line = sr.ReadToEnd()
line = "[" & line & "]"
Dim jArray__1 = JArray.Parse(line)
For Each item In jArray__1.SelectToken("[0].results.[0].details.conditions.items.[0].products")
MessageBox.Show(item.ToString)
Next
Thak you very much guys !!
I finally did it like this...
For Each element In comment.SelectToken("details")("conditions")("items")(0)("products")
Console.WriteLine(element("name"))
Console.WriteLine(element("codeBar"))
Next

Using DataContractJsonSerializer To Parse JSON To Dynamic Type In VB.NET

I am using VB.NET to parse my SearchSpring JSON like this:
Using ms As New MemoryStream(Encoding.Unicode.GetBytes(json))
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(obj.GetType())
obj = CType(serializer.ReadObject(ms), T)
Return obj
End Using
The problem is that JSON has different types for same attribute name ("value"):
{
"field": "vanity_style_63",
"value": "Transitional",
"label": "Vanity Style: Transitional",
"filterLabel": "Vanity Style",
"filterValue": "Transitional"
},
{
"field": "vanity_width_88",
"value": {
"rangeLow": "15",
"rangeHigh": "24"
},
"label": "Vanity Width: 16\" to 24\"",
"filterLabel": "Vanity Width",
"filterValue": "16\" to 24\""
},
Sometimes it is string (in example - "Transitional"), sometimes it is an object.
I am using this class in serialization.
<DataContract()> _
Public Class FilterSummary
<DataMember(Name:="field")> _
Public Property Field As String
<DataMember(Name:="filterLabel")> _
Public Property FilterLabel As String
<DataMember(Name:="filterValue")> _
Public Property FilterValue As String
<DataMember(Name:="label")> _
Public Property Label As String
<DataMember(Name:="value")> _
Public Property Value As Object
End Class
It works when I have string there. However, when JSON has object there, I cannot access its values.
What should I do?
UPDATE:
This is how full valid JSON looks like:
{
"filterSummary": [{
"field": "vanity_width_88",
"value": {
"rangeLow": "15",
"rangeHigh": "24"
},
"label": "Vanity Width: 16\" to 24\"",
"filterLabel": "Vanity Width",
"filterValue": "16\" to 24\""
}, {
"field": "vanity_width_88",
"value": {
"rangeLow": "35",
"rangeHigh": "42"
},
"label": "Vanity Width: 35 to 42",
"filterLabel": "Vanity Width",
"filterValue": "35 to 42"
}]
}

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

error in parsing json string in javascript

I am using JSON in Javascript for first time in my project of asp.net. I am new to it.
I have successfully created a JSON string on page load and stored it in a hidden field.
Now, in Javascript when I try to eval or parse that string, it do not parse it.
Please help. Here's how I'm doing it:
var jsonText = $("#hiddenJson").val();
var jsonObject = JSON.parse(jsonText);
//var jsonObject = eval("(" + jsonText + ")");
alert(jsonObject.user[0].Gender);
//---- alert gives [object Object]
//------- value of jsonText is
"[ { "user": [ { "Gender": "M", "Minage": "28", "Maxage": "24", "MaritalStatusId": "2,3", "ChildrenPreferencesId": "0", "PersonalValueId": "1", "MinHeight": "6", "MaxHeight": "1", "BodyTypeId": "0", "ComplexionId": "0", "HealthAttributeId": "1", "SpecialCaseId": "1", "ReligionId": "3,5", "CasteId": "1,6", "MotherTongueId": "", "QualificationLevelId": "2,3", "QualificationFieldId": "", "WorkingWithId": "4,5", "ProfessionArea": "3,4", "WorkingAsId": "3,4", "IncomeId": "3", "DietId": "0", "SmokeId": "1", "DrinkId": "2", "CountryId": "4,5", "ResidencyId": "", "PartnerDescription": "" }] } ]"
if you're using double quotes for the members of the json object, then put the whole string in single quotes instead, like
var jsonText = '[ { "user": [ { "Gender": "M", "Minage": "28", "Maxage": "24", "MaritalStatusId": "2,3", "ChildrenPreferencesId": "0", "PersonalValueId": "1", "MinHeight": "6", "MaxHeight": "1", "BodyTypeId": "0", "ComplexionId": "0", "SpecialCaseId": "1", "ReligionId": "3,5" }] } ]'
Your JSON object itself is an array:
alert( jsonObject[0].user[0].Gender );
See an example at http://jsfiddle.net/GTLX3/