JSON file cannot be de-serialized - json

I am trying to use JSON script and getting error;
I have managed to deserialized JSON with single array in the row, but this script has multiple arrays in single row.
My Code;
Dim s As String = File.ReadAllText("C:\Users\sajid\source\repos\JSON_TO_DATABASE\dummy.json") 'reader.ReadToEnd '
Dim myJs = JsonConvert.DeserializeObject(Of Rootobject)(s)
https://i.ibb.co/7XRyhzk/Error.png (Error Massage)
I need this below JSON to deserialize so that i can use the data in my application and later save it to database
JSON script here;
{"SuccessResponse": {
"Head": {
"RequestId": "0b1192a115701283055003672e6b47",
"RequestAction": "GetOrder",
"ResponseType": "Order",
"Timestamp": "2019-10-03T23:45:05+05:00"
},
"Body": {
"Orders": [
{
"OrderId": 103726686259125,
"CustomerFirstName": "ABC",
"CustomerLastName": "",
"OrderNumber": 103125,
"PaymentMethod": "COD",
"Remarks": "",
"DeliveryInfo": "",
"Price": "800.00",
"GiftOption": false,
"GiftMessage": "",
"VoucherCode": "",
"CreatedAt": "2019-05-24 11:30:45",
"UpdatedAt": "2019-06-10 17:25:51",
"AddressBilling": {
"FirstName": "CBD",
"LastName": "",
"Phone": "92HJHJ2",
"Phone2": "",
"Address1": "Pakistan",
"Address2": "",
"Address3": "Punjab",
"Address4": "Lahore",
"Address5": "H",
"CustomerEmail": "",
"City": "Lahore",
"PostCode": "",
"Country": "Pakistan",
"TreeAddressId": ""
},
"AddressShipping": {
"FirstName": "BCD",
"LastName": "",
"Phone": "923UJII102",
"Phone2": "",
"Address1": "Pakistan",
"Address2": "",
"Address3": "Punjab",
"Address4": "Lahore",
"Address5": "H",
"CustomerEmail": "",
"City": "Lahore",
"PostCode": "",
"Country": "Pakistan",
"TreeAddressId": ""
},
"NationalRegistrationNumber": "",
"ItemsCount": 4,
"PromisedShippingTimes": "",
"ExtraAttributes": "",
"Statuses": [
"failed"
],
"Voucher": 75.00,
"ShippingFee": 99.00,
"TaxCode": "",
"BranchNumber": ""
}
]
}
}}
My Class Model
Public Class Rootobject
Public Property SuccessResponse As Successresponse
End Class
Public Class Successresponse
Public Property Head As Head
Public Property Body As Body
End Class
Public Class Head
Public Property RequestId As String
Public Property RequestAction As String
Public Property ResponseType As String
Public Property Timestamp As Date
Public Property TotalCount As Integer
End Class
Public Class Body
Public Property Orders() As List(Of Order)
Public Property Addressbillings() As List(Of Addressbilling)
Public Property Addressshippings() As List(Of Addressshipping)
End Class
Public Class Order
Public Property OrderId As Long
Public Property CustomerFirstName As String
Public Property CustomerLastName As String
Public Property OrderNumber As Long
Public Property PaymentMethod As String
Public Property Remarks As String
Public Property DeliveryInfo As String
Public Property Price As String
Public Property GiftOption As Boolean
Public Property GiftMessage As String
Public Property VoucherCode As String
Public Property CreatedAt As String
Public Property UpdatedAt As String
Public Property AddressBilling As Addressbilling
Public Property AddressShipping As Addressshipping
Public Property NationalRegistrationNumber As String
Public Property ItemsCount As Integer
Public Property PromisedShippingTimes As String
Public Property ExtraAttributes As String
Public Property Statuses() As String
Public Property Voucher As Single
Public Property ShippingFee As Single
Public Property TaxCode As String
Public Property BranchNumber As String
End Class
Public Class Addressbilling
Public Property FirstName As String
Public Property LastName As String
Public Property Phone As String
Public Property Phone2 As String
Public Property Address1 As String
Public Property Address2 As String
Public Property Address3 As String
Public Property Address4 As String
Public Property Address5 As String
Public Property CustomerEmail As String
Public Property City As String
Public Property PostCode As String
Public Property Country As String
Public Property TreeAddressId As String
End Class
Public Class Addressshipping
Public Property FirstName As String
Public Property LastName As String
Public Property Phone As String
Public Property Phone2 As String
Public Property Address1 As String
Public Property Address2 As String
Public Property Address3 As String
Public Property Address4 As String
Public Property Address5 As String
Public Property CustomerEmail As String
Public Property City As String
Public Property PostCode As String
Public Property Country As String
Public Property TreeAddressId As String
End Class

I am not 100% but an initial look I notice your class is not camel-casing certain things
Public Class Addressshipping
Public Class Addressbilling
Where the json is camel cased
"AddressShipping"
"AddressBilling"
SuccessResponse
I would look through both files to make sure that they're all the same.
For example your SuccessResponse:
Public Property SuccessResponse As Successresponse
vs
Public Property Addressbillings() As List(Of Addressbilling)
Public Property Addressshippings() As List(Of Addressshipping)

Related

Parsing Complex JSON string using VB.Net

I have a complex JSON as below
{
"?xml": {
"#version": "1.0",
"#encoding": "UTF-8"
},
"env:Envelope": {
"#xmlns": "http://com/ccccc",
"#xmlns:env": "http://schemas.xmlsoap.org/soap/envelope/",
"env:Header": {
"uhtHeader": {
"#xmlns": "http://com/bbbbbb",
"consumer": "XXXXX",
"auditId": "",
"sendTimestamp": "2020-07-27T13:47:53.172-05:00",
"environment": "P",
"businessService": {
"#version": "16",
"#text": "Filename"
},
"status": "success"
}
},
"env:Body": {
"srvcRspn": {
"#xmlns": "http://com/aaaaaaa",
"srvcErrList": {
"#arrayType": "srvcErrOccur[2]",
"#type": "Array",
"srvcErrOccur": [
{
"orig": "Foundation",
"rtnCd": "00",
"explCd": "000",
"desc": ""
},
{
"orig": "YYYYYYY",
"rtnCd": "0000",
"explCd": "",
"desc": ""
}
]
},
"icn": "1234567890",
"icnSufx": "01",
"adjOfc": "123",
"fln": "12345678",
"empId": {
"id1": "S",
"ssn": "abcdefghij"
},
"engInd": "C",
"xcob": {
"ssn1": "",
"ssn9": "",
"appl": ""
},
"provList": {
"#arrayType": "provOccur[2]",
"#type": "Array",
"provOccur": [
{
"tin": "123456789012345",
"nm": "ABCD EFGH",
"typSpec": "MD"
},
{
"tin": "000000000000000",
"nm": "",
"typSpec": ""
}
]
},
"newOfc": "000",
"origOfc": "",
"drg": "",
"drgAmt": "00000000000",
"totChrg": "00000046212",
"causCd": "4",
"icdVersionInd": "",
"procCdList": {
"#arrayType": "procCdOccur[5]",
"#type": "Array",
"procCdOccur": [
{
"procCd": ""
},
{
"procCd": ""
},
{
"procCd": ""
},
{
"procCd": ""
},
{
"procCd": ""
}
]
},
"atdPhysnId": {
"drNmLst": "ABCD",
"drNmFst": "EFGH",
"drNmInit": "L"
},
"provAdr": {
"adr": "1234 ABCD EFGH",
"adr2": "",
"cty": "ABCDEFG",
"st": "AB",
"zip": "123456789"
},
"attchCdList": {
"#arrayType": "attchCd[2]",
"#type": "Array",
"attchCd": [
{
"cd": ""
},
{
"cd": ""
}
]
},
"occurCdList": {
"#arrayType": "occurCdOccur[8]",
"#type": "Array",
"occurCdOccur": [
{
"cd": "12345",
"dt": "11022020"
},
{
"cd": "1234",
"dt": "11022020"
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
}
]
},
"hNr": "",
"hAdmDiagCd": "",
"heDiagCd": "",
"faclRndr": {
"nm": "",
"str": "",
"cty": "",
"st": "",
"zip": ""
},
"emergInd": "",
"autoAccInd": "",
"autoAccSt": "",
"empRelInd": "",
"othrDiagList": {
"#arrayType": "othrDiagOccur[3]",
"#type": "Array",
"othrDiagOccur": [
{
"desc": ""
},
{
"desc": ""
},
{
"desc": ""
}
]
},
"nbrInsCnt": "1",
"insList": {
"#arrayType": "insOccur[1]",
"#type": "Array",
"insOccur": {
"payrNm": "ABCDEF",
"empId": "12345678",
"grpId": "",
"prrPay": "00000000000"
}
},
"typ1varList": {
"nbrLnCnt": "2",
"lnList": {
"#arrayType": "lnOccur[2]",
"#type": "Array",
"lnOccur": [
{
"plcSrvc": "AB",
"frmSrvcDt": "2020-04-21",
"toSrvcDt": "2020-04-21",
"srvcCd": "123456",
"chrgAmt": "00000024200",
"cmCd": "",
"spltLnInd": "N"
},
{
"plcSrvc": "CD",
"frmSrvcDt": "2020-04-21",
"toSrvcDt": "2020-04-21",
"srvcCd": "AA123",
"chrgAmt": "00000005877",
"cmCd": "",
"spltLnInd": "N"
}
]
}
},
"authEngTkn": "",
"adjId": ""
}
}
}
}
I need to parse this using VB.net in my application and get the values.
I have tried making the below classes using JSONUtils, but getting 4 errors
Public Class Xml
Public Property #version As String
Public Property #encoding As String
End Class
Public Class BusinessService
Public Property #version As String
Public Property #text As String
End Class
Public Class UhtHeader
Public Property #xmlns As String
Public Property consumer As String
Public Property auditId As String
Public Property sendTimestamp As DateTime
Public Property environment As String
Public Property businessService As BusinessService
Public Property status As String
End Class
Public Class EnvHeader
Public Property uhtHeader As UhtHeader
End Class
Public Class SrvcErrOccur
Public Property orig As String
Public Property rtnCd As String
Public Property explCd As String
Public Property desc As String
End Class
Public Class SrvcErrList
Public Property #arrayType As String
Public Property #type As String
Public Property srvcErrOccur As SrvcErrOccur()
End Class
Public Class EmpId
Public Property id1 As String
Public Property ssn As String
End Class
Public Class Xcob
Public Property ssn1 As String
Public Property ssn9 As String
Public Property appl As String
End Class
Public Class ProvOccur
Public Property tin As String
Public Property nm As String
Public Property typSpec As String
End Class
Public Class ProvList
Public Property #arrayType As String
Public Property #type As String
Public Property provOccur As ProvOccur()
End Class
Public Class ProcCdOccur
Public Property procCd As String
End Class
Public Class ProcCdList
Public Property #arrayType As String
Public Property #type As String
Public Property procCdOccur As ProcCdOccur()
End Class
Public Class AtdPhysnId
Public Property drNmLst As String
Public Property drNmFst As String
Public Property drNmInit As String
End Class
Public Class ProvAdr
Public Property adr As String
Public Property adr2 As String
Public Property cty As String
Public Property st As String
Public Property zip As String
End Class
Public Class AttchCd
Public Property cd As String
End Class
Public Class AttchCdList
Public Property #arrayType As String
Public Property #type As String
Public Property attchCd As AttchCd()
End Class
Public Class OccurCdOccur
Public Property cd As String
Public Property dt As String
End Class
Public Class OccurCdList
Public Property #arrayType As String
Public Property #type As String
Public Property occurCdOccur As OccurCdOccur()
End Class
Public Class FaclRndr
Public Property nm As String
Public Property str As String
Public Property cty As String
Public Property st As String
Public Property zip As String
End Class
Public Class OthrDiagOccur
Public Property desc As String
End Class
Public Class OthrDiagList
Public Property #arrayType As String
Public Property #type As String
Public Property othrDiagOccur As OthrDiagOccur()
End Class
Public Class InsOccur
Public Property payrNm As String
Public Property empId As String
Public Property grpId As String
Public Property prrPay As String
End Class
Public Class InsList
Public Property #arrayType As String
Public Property #type As String
Public Property insOccur As InsOccur
End Class
Public Class LnOccur
Public Property plcSrvc As String
Public Property frmSrvcDt As String
Public Property toSrvcDt As String
Public Property srvcCd As String
Public Property chrgAmt As String
Public Property cmCd As String
Public Property spltLnInd As String
End Class
Public Class LnList
Public Property #arrayType As String
Public Property #type As String
Public Property lnOccur As LnOccur()
End Class
Public Class Typ1varList
Public Property nbrLnCnt As String
Public Property lnList As LnList
End Class
Public Class SrvcRspn
Public Property #xmlns As String
Public Property srvcErrList As SrvcErrList
Public Property icn As String
Public Property icnSufx As String
Public Property adjOfc As String
Public Property fln As String
Public Property empId As EmpId
Public Property engInd As String
Public Property xcob As Xcob
Public Property provList As ProvList
Public Property newOfc As String
Public Property origOfc As String
Public Property drg As String
Public Property drgAmt As String
Public Property totChrg As String
Public Property causCd As String
Public Property icdVersionInd As String
Public Property procCdList As ProcCdList
Public Property atdPhysnId As AtdPhysnId
Public Property provAdr As ProvAdr
Public Property attchCdList As AttchCdList
Public Property occurCdList As OccurCdList
Public Property hNr As String
Public Property hAdmDiagCd As String
Public Property heDiagCd As String
Public Property faclRndr As FaclRndr
Public Property emergInd As String
Public Property autoAccInd As String
Public Property autoAccSt As String
Public Property empRelInd As String
Public Property othrDiagList As OthrDiagList
Public Property nbrInsCnt As String
Public Property insList As InsList
Public Property typ1varList As Typ1varList
Public Property authEngTkn As String
Public Property adjId As String
End Class
Public Class EnvBody
Public Property srvcRspn As SrvcRspn
End Class
Public Class EnvEnvelope
Public Property #xmlns As String
Public Property #xmlns:env As String
Public Property env:Header As EnvHeader
Public Property env:Body As EnvBody
End Class
Public Class Example
Public Property ?xml As Xml
Public Property env:Envelope As EnvEnvelope
End Class
The errors are listed below:
'Public Property As String' and 'Public Property As Object' cannot overload each other because they differ only by return types. generating for the lines like
Public Property #xmlns As String
'Public Property As String' has multiple definitions with identical signatures.' generating for the lines like
Public Property #version As String
'Declaration expected.' generating for the lines like
Public Property env:Header As EnvHeader
'Identifier expected.' generating for the lines like
Public Property #type As String
I am very much new in this concept and have very small idea about how to parse JSON using VB.Net.
Any help is much appreciated as I have been assigned this project suddenly with a very tight client deliverable timeline. Thanks in advance

Json Deserialize Nested Objects in Vb (Newtonsoft)

Basically, I'm trying to get data from the API.
My JSON is :
[
{
"id": 101,
"items": [
{
"id": 91,
"quantity": 141,
"size": "12",
"assigned": false,
"item": {
"pk": 27,
"title": "test title",
"description": "test description",
"designer": "designer",
"category": 4,
"size": "12,14,16",
"image": "media/products/indir.jpg",
"price": 31.0,
"resin_gr": 31.0
}
},
{
"id": 92,
"quantity": 18,
"size": "14",
"assigned": false,
"item": {
"pk": 26,
"title": "Bileklik 5",
"description": "bileklik",
"designer": "designer",
"category": 2,
"size": "12,14,16",
"image": "media/products/NB00316.png",
"price": 50.0,
"resin_gr": 14.0
}
}
]
}
]
My Classes are :
Public Class Orders
Public Property id As Integer
Public Property items As IEnumerable(Of OrderItems)
End Class
Public Class OrderItems
Public Property id As Integer
Public Property quantity As String
Public Property size As String
Public Property assigned As String
Public Property item As List(Of OrderProduct)
End Class
Public Class OrderProduct
Public Property pk As Integer
Public Property title As String
Public Property description As String
Public Property designer As String
Public Property category As String
Public Property size As String
Public Property image As String
Public Property price As String
Public Property resin_gr As String
End Class
I'm trying to parse JSON like this :
Dim result As IEnumerable(Of Orders) = JsonConvert.DeserializeObject(Of IEnumerable(Of Orders))(JSONDATA)
I'm getting error on Path '[0].items[0].item.pk', line 1, position 86.
What i tried :
i changed orders.item to list but nothing changed.
what shall i do about this ?
Public Class Orders
Public ID As Integer
Public Items As IEnumerable(Of OrderItems)
End Class
Public Class OrderItems
Public ID As Integer
Public quantity As Integer
Public size As Integer
Public assigned As Boolean
Public Item As OrderProduct
End Class
Public Class OrderProduct
Public pk As Integer
Public title As String
Public description As String
Public designer As String
Public category As Integer
Public size As String
Public image As String
Public price As Double
Public resin_gr As Double
End Class
Edit: like A Friend commented, This works because you were trying to parse an object as a list here:
Public Property item As List(Of OrderProduct)
When it needed to be
Public Item As OrderProduct
Somehow I missed that and solved the issue when I re-created the custom objects for the specified JSON.

Iterate a deserealized .Net Object from Json to create a DataTable

I've being spending a lot of time thinking about how to iterate an object from a deserealized json which has many items, subitems and sub-subitems. I know there are a lot of questions already posted, but I still don't get it, 'cause the examples are differrents to mine and I'm a begineer developper. I get the Json from a Web Service and I pass the Token by headers and all that stuff, but I don't know the best way to manipulate this info. I'm using Newtonsoft library, BTW.
The Json is:
{
"orders": [
{
"customer": {
"id": "string",
"externalId": "string",
"firstName": "string",
"lastName": "string",
"name": "string",
"companyName": "string",
"emailAddresses": [
"string"
],
"phones": [
{
"type": "Mobile",
"number": "string"
}
],
"addresses": [
{
"lines": [
"string"
],
"locality": [
"string"
],
"region": "string",
"postcode": "string"
}
]
},
"vehicles": [
{
"id": "string",
"description": "string",
"vin": "string",
"odometer": 0,
"tag": "string",
"nextServiceDue": "2015-07-14T10:08:15Z",
"registrationTestDue": "2015-07-14T10:08:15Z",
"brand": "string",
"extendedWarrantyEndDate": 0,
"contractEndDate": 0,
"transmissionCode": "string",
"engineCode": "string",
"bodyType": "string",
"paintCode": "string",
"modelCode": "string",
"references": [
{
"key": "string",
"value": "string"
}
]
}
],
"employees": [
{
"id": "string",
"name": "string",
"type": "Technician"
}
],
"operations": [
{
"id": "35955",
"code": "RWB",
"externalCode": "RACS",
"description": "431151: Front Shock Absorber Assembly (One Side), Repair/Replace",
"isNew": true,
"labour": {
"pricing": {
"totals": {
"total": 0
}
},
"times": [
{
"quantity": 1.2
}
]
}
}
],
"parts": [
{
"number": "string",
"quantity": 1,
"quantityUnitOfMeasure": "Hour",
"description": "string",
"vehicleId": "string",
"pricing": {
"totals": {
"total": 0
}
}
}
]
}
],
"paging": {
"page": 0,
"morePages": true,
"resultCount": 0,
"pageCount": 0
}
}
And the Code for getting the json properties is:
Public Class Rootobject
Public Property orders() As Order
Public Property paging As Paging
End Class
Public Class Paging
Public Property page As Integer
Public Property morePages As Boolean
Public Property resultCount As Integer
Public Property pageCount As Integer
End Class
Public Class Order
Public Property customer As Customer
Public Property vehicles() As Vehicle
Public Property employees() As Employee
Public Property operations() As Operation
Public Property parts() As Part
End Class
Public Class Customer
Public Property id As String
Public Property externalId As String
Public Property firstName As String
Public Property lastName As String
Public Property name As String
Public Property companyName As String
Public Property emailAddresses() As String
Public Property phones() As Phone
Public Property addresses() As Address
End Class
Public Class Phone
Public Property type As String
Public Property number As String
End Class
Public Class Address
Public Property lines() As String
Public Property locality() As String
Public Property region As String
Public Property postcode As String
End Class
Public Class Vehicle
Public Property id As String
Public Property description As String
Public Property vin As String
Public Property odometer As Integer
Public Property tag As String
Public Property nextServiceDue As Date
Public Property registrationTestDue As Date
Public Property brand As String
Public Property extendedWarrantyEndDate As Integer
Public Property contractEndDate As Integer
Public Property transmissionCode As String
Public Property engineCode As String
Public Property bodyType As String
Public Property paintCode As String
Public Property modelCode As String
Public Property references() As Reference
End Class
Public Class Reference
Public Property key As String
Public Property value As String
End Class
Public Class Employee
Public Property id As String
Public Property name As String
Public Property type As String
End Class
Public Class Operation
Public Property id As String
Public Property code As String
Public Property externalCode As String
Public Property description As String
Public Property isNew As Boolean
Public Property labour As Labour
End Class
Public Class Labour
Public Property pricing As Pricing
Public Property times() As Time
End Class
Public Class Pricing
Public Property totals As Totals
End Class
Public Class Totals
Public Property total As Integer
End Class
Public Class Time
Public Property quantity As Single
End Class
Public Class Part
Public Property number As String
Public Property quantity As Integer
Public Property quantityUnitOfMeasure As String
Public Property description As String
Public Property vehicleId As String
Public Property pricing As Pricing1
End Class
Public Class Pricing1
Public Property totals As Totals1
End Class
Public Class Totals1
Public Property total As Integer
End Class
And I deserealize the Json and i've traying this, an example:
Dim JsonObject As List(Of Rootobject) = JsonConvert.DeserializeObject(Of List(Of Rootobject))(_JsonString)
For Each item In JsonObject
_PagPage = item.paging.page
_PagMorePag = item.paging.morePages
_PagResCount = item.paging.resultCount
_PagPagCount = item.paging.pageCount
Next
I tried to use Lists like List(Of Rootobject) or List(Of List(Of Dictionary(Of Rootoobject)), but it's still not working.
If you could to help me out i'd really appreciate it.

VB.NET deserialize Newtonsoft JSON into object dynamically

ANSWER given describes using LINQ to JSON and the JObject to convert from JSON to a workable object on the fly. Below is the completed code that takes me from my JSON to a workable object, followed by the original question.
'Parse string of JSON data into a JObject that can be accessed via VB.NET
Dim resultSet As JObject = JObject.Parse(responseBody)
'Data can be accessed as seen below
Dim cpu As String = CType(resultSet("KeyName"), String)
=========================================================================
I have a web app that will be making several API calls to a service called inContact (http://www.incontact.com/)
Each of the API calls will be receiving an HTTP response filled with JSON formatted in this way:
{
"resultSet": {
"_links": {
"self": "string",
"next": "string",
"previous": "string"
},
"businessUnitId": 0,
"lastPollTime": "2016-11-08T21:45:46.510Z",
"totalRecords": 0,
"agents": [
{
"agentId": 0,
"userName": "string",
"firstName": "string",
"middleName": "string",
"lastName": "string",
"emailAddress": "string",
"isActive": true,
"teamId": 0,
"teamName": "string",
"reportToId": 0,
"reportToName": "string",
"isSupervisor": true,
"lastLogin": "2016-11-08T21:45:46.510Z",
"lastUpdated": "2016-11-08T21:45:46.510Z",
"location": "string",
"custom1": "string",
"custom2": "string",
"custom3": "string",
"custom4": "string",
"custom5": "string",
"internalId": "string",
"profileId": 0,
"profileName": "string",
"timeZone": "string",
"country": "string",
"countryName": "string",
"state": "string",
"city": "string",
"chatRefusalTimeout": 0,
"phoneRefusalTimeout": 0,
"workItemRefusalTimeout": 0,
"defaultDialingPattern": 0,
"defaultDialingPatternName": "string",
"teamDefaultMaxChats": true,
"maxConcurrentChats": 0,
"notes": "string",
"createDate": "2016-11-08T21:45:46.510Z",
"inactiveDate": "2016-11-08T21:45:46.510Z",
"hireDate": "2016-11-08T21:45:46.510Z",
"terminationDate": "2016-11-08T21:45:46.510Z",
"rehireStatus": true,
"employmentType": 0,
"employmentTypeName": "Full-Time",
"referral": "string",
"atHome": true,
"hiringSource": "string",
"ntLoginName": "string",
"scheduleNotification": "5",
"federatedId": "string",
"sipUser": "string",
"useTeamMaxEmailInboxCount": true,
"maxEmailInboxCount": 0
}
]
}
}
I am deserializing the JSON with Newtonsoft. However, with each different call there will be different key/value pairs, such as this:
{
"resultSet": {
"businessUnitId": 0,
"lastPollTime": "2016-11-08T21:45:46.604Z",
"teams": [
{
"teamId": 0,
"teamName": "string",
"isActive": true,
"description": "string",
"notes": "string",
"lastUpdateTime": "2016-11-08T21:45:46.604Z",
"inViewEnabled": true,
"wfoEnabled": true,
"wfmEnabled": true,
"qmEnabled": true,
"maxConcurrentChats": 0,
"agentCount": 0,
"maxEmailInboxCount": true,
"inViewGamificationEnabled": true,
"inViewChatEnabled": true,
"inViewLMSEnabled": true,
"analyticsEnabled": true
}
],
"agents": [
{
"agentId": 0,
"firstName": "string",
"lastName": "string"
}
]
}
}
I currently am taking in the HTTP response and deserializing the JSON to create a workable .NET object. To do so this is my shortened code, omitting the HTTP request, assuming the request was successful:
If Not String.IsNullOrEmpty(responseBody) Then
' Success. Do something with the response.
'Declare object for holding the JSON from the API call for this call only (class does not fit other calls)
Dim resultSet As GetAgentsAPICall = New GetAgentsAPICall
'Deserialize JSON response into the new resultSet object
resultSet = JsonConvert.DeserializeObject(responseBody)
The issue is that I need a specific class for each API call, instead of just being able to take a string with JSON formatting and throw it into an object with properties matching the key/values. Below is the class I have that takes in just the above API call (the first one listed, longer in length):
Public Class GetAgentsAPICall
Public Property resultSet As Resultset
End Class
Public Class Resultset
Public Property _links As _Links
Public Property businessUnitId As Integer
Public Property lastPollTime As Date
Public Property totalRecords As Integer
Public Property agents() As Agent
End Class
Public Class _Links
Public Property self As String
Public Property _next As String
Public Property previous As String
End Class
Public Class Agent
Public Property agentId As Integer
Public Property userName As String
Public Property firstName As String
Public Property middleName As String
Public Property lastName As String
Public Property emailAddress As String
Public Property isActive As Boolean
Public Property teamId As Integer
Public Property teamName As String
Public Property reportToId As Integer
Public Property reportToName As String
Public Property isSupervisor As Boolean
Public Property lastLogin As Date
Public Property lastUpdated As Date
Public Property location As String
Public Property custom1 As String
Public Property custom2 As String
Public Property custom3 As String
Public Property custom4 As String
Public Property custom5 As String
Public Property internalId As String
Public Property profileId As Integer
Public Property profileName As String
Public Property timeZone As String
Public Property country As String
Public Property countryName As String
Public Property state As String
Public Property city As String
Public Property chatRefusalTimeout As Integer
Public Property phoneRefusalTimeout As Integer
Public Property workItemRefusalTimeout As Integer
Public Property defaultDialingPattern As Integer
Public Property defaultDialingPatternName As String
Public Property teamDefaultMaxChats As Boolean
Public Property maxConcurrentChats As Integer
Public Property notes As String
Public Property createDate As Date
Public Property inactiveDate As Date
Public Property hireDate As Date
Public Property terminationDate As Date
Public Property rehireStatus As Boolean
Public Property employmentType As Integer
Public Property employmentTypeName As String
Public Property referral As String
Public Property atHome As Boolean
Public Property hiringSource As String
Public Property ntLoginName As String
Public Property scheduleNotification As String
Public Property federatedId As String
Public Property sipUser As String
Public Property useTeamMaxEmailInboxCount As Boolean
Public Property maxEmailInboxCount As Integer
End Class
I'm trying to avoid having 20 or 30 similar lengthy classes prebuilt, and instead build a modifiable list or object on the fly. I will need to take the values and either store them in a database or modify them and use another API call to POST the values back. Does anyone have a best practice, or am I stuck with 20-30 huge class definitions?
Thanks for your time!
Parse it with a JObject, which can also be queried using LINQ (see Newtonsoft's LINQ to JSON API, which sits under the Newtonsoft.Json.Linq namespace):
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
The example is in C#, but you can find relevant VB.NET answers on StackOverflow (have a look at the answer here, for example).

Json/Apex: Assigning values to nodes on the Json Array

I have an apex code that defines the JSON structure. I would like to seek for advice on how I will be able to assign values to the string fields on the JSON using Apex. The JSON will have an array (PackageData) which contains the fields that should contain the values
Apex code:
public class Shipment{
public PackageData[] PackageData;
}
public class PackageData{
public Packaging Packaging;
public Dimensions Dimensions;
public PackageWeight PackageWeight;
}
public class Packaging{
public string Code;
}
public class Dimensions{
public UnitOfMeasurement UnitOfMeasurement;
public string Length;
public string Width;
public string Height;
}
public class UnitOfMeasurement{
public string Code;
}
public class PackageWeight{
public UOM UOM;
public string Weight;
}
public class UOM{
public string Code;
}
JSON:
{
"PackageData": [
{
"Packaging": {
"Code": ""
},
"Dimensions": {
"UnitOfMeasurement": {
"Code": ""
},
"Length": "",
"Width": "",
"Height": ""
},
"PackageWeight": {
"UOM": {
"Code": ""
},
"Weight": ""
}
}
]
}
JSON are always string, so there are a parser which parse object to JSON String and vice versa
Parser does it's job and automatically parse to String, You need not worry for that
Json to Object:
ClassName objName = (ClassName) System.JSON.deserialize(jsonString, ClassName.class);
Object to Json:
String jsonString = System.JSON.serialize(objName);