RUBY parse nested JSON Object - arrays

I have a ruby script that works pretty well. I'm parsing JSON from an API and passing it into and array.
Most of the top elements parse fine. But I have a nested object that looks like this after its a hash...
I did and inspect on it and outputted the current data object I'm looking at.
orf1: ["displayValue", "DNAORF999-N9, DNAORF888-N9, DNAORF777-N9, DNAORF444-N9"]
orf1_inspect: ["displayValue", "DNAORF999-N9, DNAORF888-N9, DNAORF777-N9, DNAORF444-N9"]
orf1: ["isMulti", true]
orf1_inspect: ["isMulti", true]
orf1: ["textValue", "DNAORF999-N9, DNAORF888-N9, DNAORF777-N9, DNAORF444-N9"]
orf1_inspect: ["textValue", "DNAORF999-N9, DNAORF888-N9, DNAORF777-N9, DNAORF444-N9"]
orf1: ["type", "entity_link"]
orf1_inspect: ["type", "entity_link"]
orf1: ["value", ["seq_dfdfdfdfd", "seq_fdfdfd", "seq_fdfdfdd", "seq_jfdfdfd"]]
Here is the section of code that returns the above..Let me know if you need more info?
if row["fields"]["ORF"].nil? || row["fields"]["ORF"].empty?
orf = nil
else
row["fields"]["ORF"].each do |orf1|
puts 'orf1: ' + orf1.to_s
orfinspect = orf1.inspect
puts 'orf1_inspect: ' + orfinspect
end
end
I cant seem to parse oput the individual values.
I need to get the values/data from these fields... displayValue, isMulti, textValue, type, and value
Ive tried all kinds of approaches.. Some give conversion errors. I can use orf1.first and that works... but its only part of it...
Even this will get me the header for textvalue
orf = orf1[0]["textValue"]
puts 'orf: ' + orf.to_s
here is the inspect on row["fields"]["ORF"].inspect if it helps..
{
"displayValue" => "DNAORF888-N9, DNAORF999-N9, DNAORF444-N9, DNAORF321-N9, DNAORF111-N9, DNAORF777-N9, DNAORF222-N9, DNAORF425-N9, DNAORF122-N9",
"isMulti" => true,
"textValue" => "DNAORF888-N9, DNAORF999-N9, DNAORF444-N9, DNAORF321-N9, DNAORF111-N9, DNAORF777-N9, DNAORF222-N9, DNAORF425-N9, DNAORF122-N9", "type"=>"entity_link",
"value" => ["seq_jddddaA2", "seq_sfgsfff", "seq_osfsffs", "seq_fsdfsd", "seq_fsdfsd", "seq_fsfsfsfs", "seq_sfsfss", "seq_sfsfsf", "seq_sfsfs"]
}
This seems to work. Is this the best approach?
row["fields"]["ORF"].each do |key,value|
if key == 'displayValue'
unless value.nil?
orf_displayValue=value
end
end
if key == 'isMulti'
unless value.nil?
orf_isMulti=value
end
end
if key == 'textValue'
unless value.nil?
orf_textValue=value
end
end
if key == 'type'
unless value.nil?
orf_type=value
end
end
if key == 'value'
unless value.nil?
orf_value=value
end
end
end
end
But I would need to do this for each field. I feel like there is a better way..

As the error says:
can't convert Symbol into Integer
textValue is of type Symbol and when you are looping over data you end with first key and value which is displayValue and DNAORF004-N9 and inside do end block you are accessing DNAORF004-N9 index with textValue which is Symbol which is not possible it should be integer as the error states.
data = {"displayValue"=>"DNAORF004-N9", "isMulti"=>true, "textValue"=>"DNAORF001-N9", "type"=>"entity_link", "value"=>["seq_fdfdf", "seq_9fdfdfdfd"]}
datasequences = [ :displayValue, :textValue ]
datasequences.each do |textValue|
puts "textValue is #{textValue.inspect}"
data.each do |key, value|
puts "\t#{value[textValue]} at #{key}"
end
end
To resolve the issue you can change the code as below:
data = {"displayValue"=>"DNAORF004-N9", "isMulti"=>true, "textValue"=>"DNAORF001-N9", "type"=>"entity_link", "value"=>["seq_fdfdf", "seq_9fdfdfdfd"]}
datasequences = [ :displayValue, :textValue ]
# changing all keys from string to symbol
data = data.transform_keys(&:to_sym)
datasequences.each do |textValue|
puts "textValue is #{textValue.inspect}"
puts "Value: #{data[textValue]}"
end
value = {
"dnaSequences": [
{
"aliases": [],
"annotations": [],
"apiURL": "https://url",
"archiveRecord": nil,
"authors": [
{
"handle": "dsdsd",
"id": "ent_dsdsd",
"name": "dsdsd"
}
],
"bases": "",
"createdAt": "2020-07-14T21:39:26.991794+00:00",
"creator": {
"handle": "dsds",
"id": "ent_dsdsd",
"name": "dsdd Fdsdsdso"
},
"customFields": {},
"dnaAlignmentIds": [],
"entityRegistryId": "MOUSE006",
"fields": {
"Identical mouses": {
"displayValue": nil,
"isMulti": false,
"textValue": nil,
"type": "part_link",
"value": nil
},
"Library Constructed By": {
"displayValue": "dsdsd",
"isMulti": false,
"textValue": "dsdsd",
"type": "dropdown",
"value": "sfso_dsdsd"
},
"Library Construction Date": {
"displayValue": "2020-06-01",
"isMulti": false,
"textValue": "2020-06-01",
"type": "date",
"value": "2020-06-01"
},
"Library Description": {
"displayValue": "dsdsdds",
"isMulti": false,
"textValue": "dsdsdsd",
"type": "text",
"value": "dsdsdsdsd"
},
"Library Sample Source": {
"displayValue": "dsdsds",
"isMulti": false,
"textValue": "dsdsdsds",
"type": "dropdown",
"value": "sfso_dsdsdsd"
},
"ORF": {
"displayValue": "DNAORF004-N9, DNAORF005-N9, DNAORF008-N9, DNAORF001-N9",
"isMulti": true,
"textValue": "DNAORF004-N9, DNAORF005-N9, DNAORF008-N9, DNAORF001-N9",
"type": "entity_link",
"value": [
"seq_aaaaaa",
"seq_bbbbbb",
"seq_ccccc",
"seq_ddddd"
]
},
"Re-Run ORF?": {
"displayValue": nil,
"isMulti": false,
"textValue": nil,
"type": "dropdown",
"value": nil
},
"Sampling GPS Coordinates": {
"displayValue": nil,
"isMulti": false,
"textValue": nil,
"type": "text",
"value": nil
},
"Sequencing Approach": {
"displayValue": "Single Sequence",
"isMulti": false,
"textValue": "Single Sequence",
"type": "dropdown",
"value": "gfgf"
},
"Sequencing Method": {
"displayValue": "gfgf fgfgfg",
"isMulti": false,
"textValue": "gfgf gfgfg",
"type": "dropdown",
"value": "sfsogfgfg_irlx6NfZ"
}
},
"folderId": "gfgfg",
"id": "gfgfgf",
"isCircular": false,
"length": 25129,
"modifiedAt": "2022-04-05T17:06:25.491926+00:00",
"name": "COPE03-P19",
"primers": [],
"registrationOrigin": {
"originEntryId": nil,
"registeredAt": "2020-07-14T22:15:09.541243+00:00"
},
"registryId": "gfgfgfg",
"schema": {
"id": "ps_fdfdfd",
"name": "mouse"
},
"translations": [],
"url": "hyyps:///COPE/f//edit",
"webURL": "https://url"
}
]
}
datasequences = [ :displayValue, :isMulti, :textValue, :type, :value ]
result = value["dnaSequences".to_sym].map do |v|
row = {}
if v.key?(:fields) && v[:fields].key?(:ORF)
datasequences.map do |key|
row[key] = v[:fields][:ORF][key.to_sym]
end
end
row
end
puts result
Note: Tested with Ruby 3.0.0

Related

How to filter JSON data based on another JSON data in typescript

I have 2 JSON Data 1. Payers 2. Rules. I need to filter Payers JSON data based on PayerId from Rules JSON data.
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}}
Rules JSON file
{
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
}]}
I need to filter Payers JSON data based on Rules JSON data if PayerID matches
I need output like below
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "34567",
"name": "Test Payer3"
}
}
How to filter?
You can use Array.filter like that (based on your data structure):
const filteredPayers = payersObj.Payers.filter((p) => rulesObj.Rules[0].Criteria[0].payerId.includes(p.payerId));
I can't figure out why your Rules json looks like this, I guess you have multiple rules. If so, you will need to iterate over each rule and invoke includes. Same for Criteria.
Code will check each rule and each critirias
and will return payers if payerId found in any of the given rules of any criteria
const payers = {
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}]}
const rules = {
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
]
}
const data = payers.Payers.filter(payer => rules.Rules.findIndex(rule => rule.Criteria.findIndex(criteria => criteria.payerId.includes(payer.payerId)) != -1) !== -1)
console.log(data)

How to update a field in Fauna Database

I am working in fauna DB. I have a confusion for writing an query to update a field . From the given array object I want to update the Boolean fields ( "presentation", "keyTakeaways", "whitepaper", "downloadAll") with the reference to the SegmentAnonymousID. I am adding the code that I tried. Can someone help me to sort out the problem.
[{
"ref": Ref(Collection("Downloads"), "322568726157197900"),
"ts": 1643884359510000,
"data": {
"SegmentAnonymousID": "57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a",
"response": {
"firstname": "test ",
"lastname": "test 1",
"email": "test#gmail.com",
"company": "test",
"presentation": false,
"keyTakeaways": false,
"whitepaper": false,
"downloadAll": false
}
}
},
{
"ref": Ref(Collection("Downloads"), "322484599970071113"),
"ts": 1643870069845000,
"data": {
"SegmentAnonymousID": "15ba9e0d-e646-4d31-beaa-b2a4d3eac56f",
"response": {
"firstname": "test 4",
"lastname": "test4",
"email": "test#gmail.com",
"company": "test",
"presentation": false,
"keyTakeaways": false,
"whitepaper": false,
"downloadAll": false
}
}
}]
The code I tried
const result = await faunaClient.query(
q.Update(
q.Select("ref", q.Get(q.Match(q.Index("SegmentAnonymousID"), "57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a")), { data: { response: { "presentation": true } } })
)
)
Your query has brackets in the wrong place. As written, the object containing the new data appears as the "default" value for the Select call. You'll likely have better success with this update (reformatted to show function calls and parameters better):
const result = await faunaClient.query(
q.Update(
q.Select(
"ref",
q.Get(
q.Match(
q.Index("SegmentAnonymousID"),
"57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a"
)
)
),
{
data: {
response: {
presentation: true
}
}
}
)
)

How can I remove all JSON objects that have a certain key/value pair from an array of JSON objects?

I want to filter a dataset this like:
For example here's some fake dataset:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Donna",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Tia",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tuxedo"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
I want to filter out everything that has "livesInCity": false:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
How can I do this? Is this possible?
In python I believe it's something like this, but I do not know how to get started in Swift:
people = [person for person in people if person.livesInCity == True]
Also, how can I filter this data set above to look like this - I want to categorize by type in name.
{
"tabby": ["Sakura", "Linn"],
"tuxedo": ["Dora"],
}
Any help will be very appreciated!
As already mentioned in the comments, you can't work directly on JSON objects in Swift. They need to be converted first.
You can parse your JSON to a Swift object and then perform filtering, grouping etc.
struct Person: Codable {
let name: String
let hasChildren: Bool
let livesInCity: Bool
let pets: [Pet]
}
struct Pet: Codable {
let cats: [String]
let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)
Then you can filter your parsedObjects:
let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })
or in shorter (swiftier) version:
let filteredObjects = parsedObjects.filter { $0.livesInCity }
You can also try to group by pet type:
var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
person.pets.forEach { pet in
if let _ = groupedDict[pet.type] {
groupedDict[pet.type]!.append(person.name)
} else {
groupedDict[pet.type] = [person.name]
}
}
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]
If at any point you want to convert your objects back to JSON you can use:
let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}
Note
For the sake of simplicity I used forced optional unwrapping (!) when decoding/encoding objects. You may want to use do-try-catch instead (to catch errors).

Calling parse function in swift fails

I am working on a food delivery app, which uses parse as its backend. I am facing a problem while calling the placeOrder API through
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in}
Please have a look at the JSON which I need to post below.
{
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": {
"menuItems": [{
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [{
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
}],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": {
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
},
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
}],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": {
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
}
},
"unavailable_option": "restaurant_recommendation"
}
And below is the Swift code which I have used to make pass it.
let storeInfo: Dictionary = [CartStoreId: self.cartStoreId, CartStoreName: self.cartRestaurantName, CartStoreImage: self.cartStoreImage, CartStoreCuisine: self.cartStoreCuisine, CartStoreDescription: self.cartStoreDescription, CartStoreRating: self.cartStoreRating, CartStoreDelivery: self.cartStoreDelivery, Takeout: self.takeOut, Address: self.address, Slugname: self.slugName, MultipleLocation: self.multipleLocation, CartStoreDeliveryFee: self.cartStoreDelivery, CartStoreServes: self.cartStoreServes, Busy: self.busy, CartStoreSeoSlug: self.cartStoreSeoSlug] as Dictionary
let subMenuItem = ["id": "zaOo6G4KSV", "name": "Beef", "price": 12, "desc": "Fillings?", "voice_read_submi_label":"bf", "voice_read_submi_option":false, "disabled": false] as [String: Any]
let ordersDictionary = [
"id" : "1234",
"title" : "Test",
"menuTitle" : "MenuName",
"price" : 23,
"qty" : 2,
"storeId" : 23,
"orderType" : "standard",
"taxState" : 0.22,
"enable" : true,
"menuTypeName" : "Type Name",
"voice_read_mi_label":"fdfs",
"voice_read_mi_option":"false",
"submenuitem": subMenuItem,
"storeInfo": storeInfo
] as Dictionary
let timeData = ["day" : 17-06-2019, "time": "11:00 AM", "tz": "America/Los_Angeles"] as Dictionary
let data = ["menuItems": ordersDictionary, "lastOrderType": "takeout", "searchedAddress": "takeout", "timeData" : timeData] as Dictionary
let params = [UserId: self.userId, "source":"card_1EVYuOEynlyM6L4SHgBMJYRQ", "data": data, "unavailable_option":"restaurant_recommendation","_ApplicationId":"6EuadToYoFGJhI1sX8XnuFBz9tp9l3yH6HxzzXZO", "_JavaScriptKey":"rQkALu9saFtF2oq9yCibyw6mEcs3PVqct3uuP6vg", "_ClientVersion":"js1.6.14", "_InstallationId":"444ec64d-5fcc-7b8e-596e-6be627892c2a",
"_SessionToken":"r:c966376120c8eca77aa63c29d5bebe1a"] as Dictionary
After all this is done I call the parse function like below.
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in
if err != nil {
print(err!)
} else {
print(data!)
}
}
But this gives me error after a few seconds saying
"Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}"
I have searched the web with the error and made fixes accordingly but still no success. Please help me guys.
I noticed that your params var is not compatible with the JSON you sent, there are more fields and also missing fields. Moreover, menuItems and submenuItem are an Array in your JSON and an Object in your code. It is probably making the cloud code function to fail and you are therefore not receiving back a valid JSON. Try the following and check if it works. In the case it works, just replace the values by your vars.
let params = [
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": [
"menuItems": [[
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [[
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
]],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": [
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
],
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
]],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": [
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
]
],
"unavailable_option": "restaurant_recommendation"
]

Deserialize malformed Json returning empty arrays

Please, I use VB.NET Http Requests to read data from a webservice. It used to send data this way:
[
{
"id": 7532,
"nome": "LABOR INC.",
"isClient": false,
"personality": {
"id": 2,
"value": "CORPORATION"
},
"registryNumbers": [
{
"id": 9378,
"number": "20786790174"
}
],
"personality_id": 2
},
{
"id": 7537,
"nome": "JOSE SILVA",
"isClient": false,
"personality": {
"id": 1,
"value": "PERSON"
},
"gender": {
"id": 1,
"value": "MALE"
},
"cityOfBirth": {
"id": 355030,
"value": "SAO PAULO"
},
"nationality": {
"id": 85,
"value": "BRAZILIAN"
},
"registryNumbers": [
{
"id": 9383,
"number": "03217495388"
}
],
"personality_id": 1
}
]
It was ok because unused fields (as "gender" and "cityOfBirth" for corporations) were omitted. Since some days, however, it started to send back these fields as empty arrays ([]), like this:
{
"id": 7532,
"nome": "LABOR INC.",
"isClient": false,
"personality": {
"id": 2,
"value": "CORPORATION"
},
"gender": [],
"cityOfBirth": [],
"nationality": [],
"registryNumbers": [
{
"id": 9378,
"number": "20786790174"
}
],
"personality_id": 2
}
And because of that it misfit the destiny properties in deserialization class, because these are not (and can't be) enumerations/arrays but single objects.
My question: is there some deserialization extension or attribute I can add to my classes in order to deserialize those ([]) as null/Nothing? Special thanks if it comes in VB.NET, but I'm able to read and adapt C# as well.
That is, I'd like to know how I could make my code halt when an array is "forced" into a property that expects single objects, and do the proper treatment at this point.
Tried and solved the problem with a custom converter:
Public Class BogusArrayJsonConverter
Inherits JsonConverter
Public Overrides Function CanConvert(objectType As Type) As Boolean
Return GetType(MyRecord).IsAssignableFrom(objectType)
End Function
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
If reader.TokenType = JsonToken.StartArray Then
Return serializer.Deserialize(Of MyRecord())(reader).SingleOrDefault
Else
Return serializer.Deserialize(Of MyRecord)(reader)
End If
End Function
Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
Throw New NotImplementedException()
End Sub
End Class
Thanks to all who tried to help me.

Resources