How can I remove empty array and empty list from a JSON string?
I use vb.net and json.net to make this but json.net can't remove empty array from JSON string. My JSON string is like this:
{
"jsonrpc": "2.0",
"id": 1,
"token": "tikenname",
"method": "task.run",
"params": {
"commandList": [{
"method": "Users.new",
"params": {
"userIds": "userid",
"details": {
"credentials": {
"userName": "user",
"password": "pass"
},
"data": {
"rights": {},
"quota": {
"daily": {
"limit": {}
},
"weekly": {
"limit": {}
},
"monthly": {
"limit": {}
}
},
"wwwFilter": {}
},
"autoLogin": {
"addresses": {},
"addressGroup": {}
},
"vpnAddress": {},
"groups": {}
}
}
},
{
"method": "set.save"
}
]
}
}
for example I want to remove this section from my string
"data": {
"rights": {},
"quota": {
"daily": {
"limit": {}
},
"weekly": {
"limit": {}
},
"monthly": {
"limit": {}
}
},
"wwwFilter": {}
},
"autoLogin": {
"addresses": {},
"addressGroup": {}
},
"vpnAddress": {},
"groups": {}
And here's my class:
Public Class Account
Public Property jsonrpc As String
Public Property id As Integer
Public Property token As String
Public Property method As String
Public Property params As New AccountSetParams
End Class
Public Class AccountSetParams
Public Property commandList As New List(Of AccountSetCommandlist)
End Class
Public Class AccountSetCommandlist
Public Property method As String
Public Property params As New AccountSetUserDetails
End Class
Public Class AccountSetUserDetails
Public Property userIds() As String
Public Property details As New AccountSetDetails
Public Property domainId As String
End Class
Public Class AccountSetDetails
Public Property credentials As New AccountSetCredentials
Public Property fullName As String
Public Property data As New AccountSetData
Public Property autoLogin As New AccountSetAutologin
Public Property vpnAddress As New AccountSetVpnaddress
Public Property groups() As New AccountSetGroup
End Class
...
It does not look like Json.Net provides an easy way to exclude empty lists or arrays like you are describing. Technically, most of the objects that you want to exclude are NOT empty: they contain other objects [that contain other objects ...] that are empty.
So to accomplish this, you will need to use recursive descent to filter out the "non-useful" information. I think probably the best approach is to first load your object graph into a JObject (or JArray), then recursively copy non-empty elements into a new JObject (or JArray), working your way from the deepest levels upward. You can then serialize the copy to get the pared-down JSON you want. This approach will allow you to handle any object structure in a generic manner.
Here is a function that should do the trick:
Function RemoveEmptyChildren(token As JToken) As JToken
If token.Type = JTokenType.Object Then
Dim copy As JObject = New JObject()
For Each prop As JProperty In token.Children(Of JProperty)()
Dim child As JToken = prop.Value
If child.HasValues Then
child = RemoveEmptyChildren(child)
End If
If Not IsEmpty(child) Then
copy.Add(prop.Name, child)
End If
Next
Return copy
ElseIf token.Type = JTokenType.Array Then
Dim copy As JArray = New JArray()
For Each child As JToken In token.Children()
If child.HasValues Then
child = RemoveEmptyChildren(child)
End If
If Not IsEmpty(child) Then
copy.Add(child)
End If
Next
Return copy
End If
Return token
End Function
Function IsEmpty(token As JToken) As Boolean
Return (token.Type = JTokenType.Array And Not token.HasValues) Or
(token.Type = JTokenType.Object And Not token.HasValues) Or
(token.Type = JTokenType.String And token.ToString() = String.Empty) Or
(token.Type = JTokenType.Null)
End Function
Here is a short example demonstrating how to use the function:
Dim jsonString As String = _
"{" + _
"""Int"" : 1," + _
"""String"" : ""Foo""," + _
"""EmptyString"" : """"," + _
"""EmptyArray"" : []," + _
"""EmptyObject"" : {}," + _
"""NullValue"" : null," + _
"""ArrayOfEmptyChildren"" : [ [], {}, """", null ]," + _
"""ChildObjectWithEmptyValues"" : {" + _
"""Array"" : []," + _
"""Object"" : {}," + _
"""Null"" : null," + _
"""String"" : """"" + _
"}," + _
"""Boolean"" : true" + _
"}"
Dim token As JToken = RemoveEmptyChildren(JToken.Parse(jsonString))
Console.WriteLine(token.ToString(Formatting.Indented))
And here is the output of the above example. Notice that only the non-empty information remains.
{
"Int": 1,
"String": "Foo",
"Boolean": true
}
Note: if you are starting from an object instead of a JSON string, you can still use this function. Just replace JToken.Parse(jsonString) in the example above with JToken.FromObject(yourObject).
Also, if you want to change what gets removed or doesn't get removed from the output, you can modify the IsEmpty function to suit your needs.
Hope this helps.
Related
Im trying to import a json to datagridview in vb.net.
{ "data":
{ "docdata":
{ "Join": [
{ "Allocated": [
{ "dt": "19-04-2022", },
{ "dt": "30-04-2022", },
{ "dt": "03-05-2022", },
{ "dt": "13-06-2022", },
{ "dt": "07-07-2022", }
]
}
}
}
}
the first "dt" value which is 19-04-2-22 is not being adding to the datagridview, instead values are being inserted from 30-04-2022
For i = 0 To Joincount - 1
For j = 0 To jsonobject.SelectToken("data.docdata.Join")(i)("Allocated").Count - 1
FrmStart.DataGridView1.Rows(i).Cells(0).Value = jsonobject.SelectToken("data.docdata.Join")(i)("Allocated")(j)("dt")
'Console.WriteLine(jsonobject.SelectToken("data.docdata.Join")(i)("Allocated")(j)("dt"))
Next
' crow += 1
FrmStart.DataGridView1.Rows.Add()
Next
In the debug window, "console.writeline" returns correct values. It is printing the first record, which is dated 19-04-2022. However, it is not inserting the same in gridview.
I'm a beginner at coding. and my way of thinking is also in its early stages, so please advise me on the best way to deal with it.
Thank you all for your efforts.#user21031252, the problem still exists even with that method however it got fixed if i changed coding.
For i = 0 To Joincount - 1
For j = 0 To jsonobject.SelectToken("data.docdata.Join")(i)("Allocated").Count - 1
jdate = jsonobject.SelectToken("data.docdata.Join")(i)("Allocated")(j)("dt")
Next
FrmStart.DataGridView1.Rows.Add(Jdate)
Next
Hopefully this will help others working with json objects.
Suggested solution after correcting the json string:
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
Dim JsonData As String = "
{ ""data"":
{ ""docdata"":
{ ""Join"":
[
{ ""Allocated"":
[
{ ""dt"": ""19-04-2022"", },
{ ""dt"": ""30-04-2022"", },
{ ""dt"": ""03-05-2022"", },
{ ""dt"": ""13-06-2022"", },
{ ""dt"": ""07-07-2022"", }
]
}
]
}
}
} "
Dim JsonObject As JObject = JObject.Parse(JsonData)
For i = 0 To JsonObject.Count - 1
For j = 0 To JsonObject.SelectToken("data.docdata.Join")(i)("Allocated").Count - 1
DataGridView1.Rows.Add(JsonObject.SelectToken("data.docdata.Join")(i)("Allocated")(j)("dt"))
Next
Next
End Sub
End Class
Public Class Allocated
Public Property dt As String
End Class
Public Class Join
Public Property Allocated As Allocated()
End Class
Public Class Docdata
Public Property Join As Join()
End Class
Public Class Data
Public Property docdata As Docdata
End Class
Public Class Example
Public Property data As Data
End Class
I'm having a problem creating a JSON array containing sub arrays in VB.Net Visual Basic. I've tried a number of different approaches, and can't figure out how to get the sub array to appear as an array (it's missing the [ and ]).
My current code (shortened here for clarity's sake) is:
Dim EEID As String = oEE.ID
Dim EEDict As New Dictionary(Of Object, Object) From {
{"EmployeeCode", EEID},
{"FirstName", Replace(oEE.firstname, ",", " ")},
{"MiddleName", Replace(oEE.middleName, ",", " ")},
{"LastName", Replace(oEE.lastname, ",", " ")},
{"Phone", oEE.homePhone},
{"EMail", oEE.emailAddress},
{"StartDate", CDate(oEE.hireDate).ToString("yyyy-MM-dd")},
}
Dim IdDict As New Dictionary(Of Object, Object) From {
{"ID", EEID & "#" & oEE.co & ".TWP"}
}
EEDict.Add("Identifiers", IdDict)
Dim VarDict As New Dictionary(Of Object, Object) From {
{"EmployeeType", oEE.empType},
{"Department", oEE.cc1},
{"Home1", "SelfEdit"}
}
Dim StateDict As New Dictionary(Of Object, Object) From {
{"EffectiveDate", DataEffDate},
{"Variables", VarDict}
}
EEDict.Add("States", StateDict)
Dim NewEEData As String = Newtonsoft.Json.JsonConvert.SerializeObject(EEDict)
This creates a serialized object like this (it's missing the [ and ] :
{
"EmployeeCode":"020000",
"FirstName":"First",
"MiddleName":"Middle",
"LastName":"Last",
"StartDate":"2003-01-01",
"Identifiers"
:{
"ID":"020000#3179.TWP"
},
"States"
:{
"EffectiveDate":"2020-11-01",
"Variables"
:{
"EmployeeType":"RFT",
"Department":"406110",
"Home1":"SelfEdit"
}
}
}
I've tried serializing the sub dictionaries before adding to the main object with:
EEDict.Add("Identifiers", Newtonsoft.Json.JsonConvert.SerializeObject(IdDict))
Dim StateDict As New Dictionary(Of Object, Object) From {
{"EffectiveDate", DataEffDate},
{"Variables", Newtonsoft.Json.JsonConvert.SerializeObject(VarDict)}
}
EEDict.Add("States", Newtonsoft.Json.JsonConvert.SerializeObject(StateDict))
And all this does is add slashes between the braces, still no [ ].
"States":"
{
\"EffectiveDate\":\"2020-11-01\",
\"Variables\":\"
{
\\\"EmployeeType\\\":\\\"RFT\\\",
\\\"Department\\\":\\\"406110\\\",
\\\"Home1\\\":\\\"SelfEdit\\\"
}\"
}"
The output should look something like this:
"States": [
{
"EffectiveDate": "Type: DateValue, Notes: YYYY-MM-DD",
"Variables":
{
"EmployeeType": "Type: StringValue",
"Title": "Type: StringValue",
"Department": "Type: StringValue",
"Home1": "Type: StringValue"
}
}
]
When I go to submit the array, it returns null error in the Identifiers (the first sub array) section, no ID found. Can someone please point me into the right direction.
You need States to be a List(of object) instead of Dictionary(of object, object)
Dim StateDict As New List(Of Object) From {
{"EffectiveDate", DataEffDate},
{"Variables", VarDict}
}
EEDict.Add("States", StateDict)
List(of object) is delimited by square brackets that you need [ { obj } ].
Object is delimited by braces { name:value }.
Dictionary(of String, Object) will do { name: { obj } }
I'm getting an error when I try to deserialize a JSON string:
Cannot deserialize the current JSON array (e.g. [1,2,3]) ...
vb.net code:
Public Class DATA
Public Property CPU As String
End Class
Dim data As DATA = JsonConvert.DeserializeObject(Of DATA)(File.ReadAllText("laptop.json"))
TextBox25.Text = DATA.CPU
The JSON file:
[
{
"spec": "CPU";
"value": "Intel Core i3-4005U"
};
{
"spec": "Speed";
"value": "1.7 GHz"
};
{
"spec": "Cache";
"value": "3MB"
};
{
"spec": "RAM";
"value": "4GB"
};
{
"spec": "Warranty Period";
"value": "1 Year"
}
]
How can I fix this error?
There are three problems here.
First, the JSON as you have shown it is invalid. Properties within JSON objects and values within JSON arrays must be separated by commas (,), not semicolons (;). See JSON.org.
Second, your JSON represents an array (or list) of items, but you are trying to deserialize into a single class. You need to deserialize into a list like this:
Dim json As String = File.ReadAllText("laptop.json")
Dim list As List(Of DATA) = JsonConvert.DeserializeObject(Of List(Of DATA))(json)
Third, the property names in the DATA class you are using do not match the JSON property names of the objects in the array. The class should be defined like this instead:
Class DATA
Public Property spec As String
Public Property value As String
End Class
Fiddle: https://dotnetfiddle.net/0aI2C3
I am currently using the Newtonsoft framework to serialize my product categories dataset into json data.
The current way i do it is:
Public Function Category() As String
Try
Dim ds As DataSet = getDataSetFromPTLSAGE("website.CategoryList", db_conx("xxxxxxxxxxxx"))
Dim string_ As String
string_ = JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented)
Return string_
Catch ex As Exception
Return ex.ToString
End Try
End Function
This works well and produces results like this:
{
"Table": [
{
"Id": "21",
"Name": "Accessories",
"URLFriendlyName": "accessories"
},
{
"Id": "06",
"Name": "Baby",
"URLFriendlyName": "baby"
},
{
"Id": "01",
"Name": "Bath & Shower",
"URLFriendlyName": "bath-shower"
},
{
"Id": "18",
"Name": "Books & Stationery",
"URLFriendlyName": "books-stationery"
}
]
}
Now what I would like to do is insert the sub categories into the json output. I can obtain the sub category data easily enough and put it into a dataset but what is the best method to have an array of objects inside the current object. The output should look like this:
{
"Table": [
{
"Id": "21",
"Name": "Accessories",
"URLFriendlyName": "accessories",
"SubCategory": [
{
"Id":"01",
"Name":"Travel",
"URLFriendlyName":"travel"
},
{
"Id":"02",
"Name":"Umbrella",
"URLFriendlyName":"umbrella"
}
]
}
]
}
Any thoughts and suggestions how i would serialise a linked datatable inside a dataset?
It was Carra's answer that lead me to this but in case anyone wants to see the final code:
Public Class Class1
Public Function Category() As String
Try
Dim _categorylist As New CategoryList
_categorylist.Categories = New List(Of Categories)
Dim ds As DataSet = getDataSetFromSQL("website.CategoryList", db_conx("xxxxxxxx"))
If ds.Tables(0).Rows.Count > 0 Then
For i = 0 To ds.Tables(0).Rows.Count - 1
Dim _category As New Categories
Dim id As String = ds.Tables(0).Rows(i)("Id").ToString.Trim
_category.Id = id
_category.Name = ds.Tables(0).Rows(i)("Name").ToString.Trim
_category.URLFriendlyName = ds.Tables(0).Rows(i)("URLFriendlyName").ToString.Trim
_category.SubCategories = New List(Of SubCategories)
Dim subDs As DataSet = getDataSetFromSQL("website.SubCategoryList", db_conx("xxxxxxxx"), "#id", id)
If subDs.Tables(0).Rows.Count > 0 Then
For x = 0 To subDs.Tables(0).Rows.Count - 1
Dim _subCategory As New SubCategories
_subCategory.Id = subDs.Tables(0).Rows(x)("Id").ToString.Trim
_subCategory.Name = subDs.Tables(0).Rows(x)("Name").ToString.Trim
_subCategory.URLFriendlyName = subDs.Tables(0).Rows(x)("URLFriendlyName").ToString.Trim
_category.SubCategories.Add(_subCategory)
Next x
End If
_categorylist.Categories.Add(_category)
Next
End If
Return JsonConvert.SerializeObject(_categorylist, Newtonsoft.Json.Formatting.Indented)
Catch ex As Exception
Return ex.ToString
End Try
End Function
End Class
Public Class CategoryList
Public Property Categories() As List(Of Categories)
End Class
Public Class Categories
Public Property Id() As String
Public Property Name() As String
Public Property URLFriendlyName() As String
Public Property SubCategories As List(Of SubCategories)
End Class
Public Class SubCategories
Public Property Id() As String
Public Property Name() As String
Public Property URLFriendlyName() As String
End Class
Please note that the function getDataSetFromSql is just a helper function I've created to help me quickly obtain stored procedure datasets from SQL
You can do it like this:
Create a class Table which contains id, name, urlfriendlyname and a List properties.
Convert your dataset to this table object.
Serialize this table object to json.
I am trying to construct POCO classes so that RestSharp can deserialize a particular JSON result.
The sticking point seems to be that the root object contains both a nb_results key, and a dictionary of other keys ("0:", "1:", etc. each with a complex value).
I have tried both Dictionary(Of Integer, mediaGalleryData) and Dictionary(Of String, mediaGalleryData). Neither works. nb_results always serializes, but the dictionary never does.
{
"nb_results": 2,
"0": {
"id": 51976254,
"title": "Bumblebee species Bombus terrestris",
"media_type_id": 1,
"creator_name": "paulrommer",
"creator_id": 201446851,
"thumbnail_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/51\/97\/62\/110_F_51976254_dVCbgGVey5xEuLkvk1e4vhnmPqxI4J0X.jpg",
"thumbnail_html_tag": "<img src=\"http:\/\/t1.ftcdn.net\/jpg\/00\/51\/97\/62\/110_F_51976254_dVCbgGVey5xEuLkvk1e4vhnmPqxI4J0X.jpg\" alt=\"Bumblebee species Bombus terrestris\" title=\"Photo: Bumblebee species Bombus terrestris\" width=\"110\" height=\"73\" \/>",
"thumbnail_width": 110,
"thumbnail_height": 73,
"affiliation_link": "http:\/\/api.fotolia.com\/id\/51976254",
"thumbnail_30_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/51\/97\/62\/30_F_51976254_dVCbgGVey5xEuLkvk1e4vhnmPqxI4J0X.jpg",
"thumbnail_30_width": 30,
"thumbnail_30_height": 20,
"thumbnail_110_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/51\/97\/62\/110_F_51976254_dVCbgGVey5xEuLkvk1e4vhnmPqxI4J0X.jpg",
"thumbnail_110_width": 110,
"thumbnail_110_height": 73,
"thumbnail_400_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/51\/97\/62\/400_F_51976254_dVCbgGVey5xEuLkvk1e4vhnmPqxI4J0X.jpg",
"thumbnail_400_width": 400,
"thumbnail_400_height": 267,
"licenses": [
{
"name": "XS",
"price": 1
},
{
"name": "S",
"price": 3
},
{
"name": "M",
"price": 5
},
{
"name": "L",
"price": 7
},
{
"name": "XL",
"price": 8
},
{
"name": "XXL",
"price": 10
},
{
"name": "X",
"price": 100
}
]
},
"1": {
"id": 44488015,
"title": "Vintage Style Birds, Bees and Banners Vector Set",
"media_type_id": 3,
"creator_name": "artnerdluxe",
"creator_id": 203491263,
"thumbnail_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/44\/48\/80\/110_F_44488015_hvEpYPw8yILDsnAi6BChYWXtzmiH6jWd.jpg",
"thumbnail_html_tag": "<img src=\"http:\/\/t1.ftcdn.net\/jpg\/00\/44\/48\/80\/110_F_44488015_hvEpYPw8yILDsnAi6BChYWXtzmiH6jWd.jpg\" alt=\"Vintage Style Birds, Bees and Banners Vector Set\" title=\"Vector: Vintage Style Birds, Bees and Banners Vector Set\" width=\"105\" height=\"110\" \/>",
"thumbnail_width": 105,
"thumbnail_height": 110,
"affiliation_link": "http:\/\/api.fotolia.com\/id\/44488015",
"thumbnail_30_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/44\/48\/80\/30_F_44488015_hvEpYPw8yILDsnAi6BChYWXtzmiH6jWd.jpg",
"thumbnail_30_width": 29,
"thumbnail_30_height": 30,
"thumbnail_110_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/44\/48\/80\/110_F_44488015_hvEpYPw8yILDsnAi6BChYWXtzmiH6jWd.jpg",
"thumbnail_110_width": 105,
"thumbnail_110_height": 110,
"thumbnail_400_url": "http:\/\/t1.ftcdn.net\/jpg\/00\/44\/48\/80\/400_F_44488015_hvEpYPw8yILDsnAi6BChYWXtzmiH6jWd.jpg",
"thumbnail_400_width": 380,
"thumbnail_400_height": 400,
"licenses": [
{
"name": "XS",
"price": 1
},
{
"name": "S",
"price": 3
},
{
"name": "M",
"price": 5
},
{
"name": "L",
"price": 7
},
{
"name": "XL",
"price": 8
},
{
"name": "XXL",
"price": 10
},
{
"name": "V",
"price": 5
},
{
"name": "XV",
"price": 40
}
]
}
}
Here are the classes I have so far:
Public Class mediaGallery
Public Property nb_results As Integer
Public Property results As Dictionary(Of String, mediaGalleryData)
End Class
Public Class mediaGalleryData
Public Property id As Integer
Public Property title As String
Public Property creator_name As String
Public Property creator_id As Integer
Public Property media_type_id As Integer
Public Property thumbnail_url As String
Public Property thumbnail_width As Integer
Public Property thumbnail_height As Integer
Public Property thumbnail_html_tag As String
Public Property thumbnail_30_url As String
Public Property thumbnail_30_width As Integer
Public Property thumbnail_30_height As Integer
Public Property thumbnail_110_url As String
Public Property thumbnail_110_width As Integer
Public Property thumbnail_110_height As Integer
Public Property thumbnail_400_url As String
Public Property thumbnail_400_width As Integer
Public Property thumbnail_400_height As Integer
Public Property licenses As List(Of licensedata)
End Class
Public Class licensedata
Public Property name As String
Public Property price As Integer
End Class
My RestSharp-consuming code:
Public Function getUserGalleryMedias(page As Integer?, nb_per_page As Integer?, thumbnail_size As Integer?, id As String, detail_level As Integer?) As mediaGallery
Dim request = New RestRequest("user/getUserGalleryMedias", Method.GET)
If page.HasValue Then request.AddParameter("page", page.Value)
If nb_per_page.HasValue Then request.AddParameter("nb_per_page", nb_per_page.Value)
If thumbnail_size.HasValue Then request.AddParameter("thumbnail_size", thumbnail_size.Value)
If Not String.IsNullOrEmpty(id) Then request.AddParameter("id", id)
If detail_level.HasValue Then request.AddParameter("detail_level", detail_level.Value)
Return Execute(Of mediaGallery)(request)
End Function
I've accomplished what I needed to do, but I had to go a bit of the long way around.
As suggested (but not very well explained) in the RestSharp documentation on the wiki, I implemented IDeserializer to handle this class specially. I had to add SimpleJson to the website separately, since it is marked Friend inside RestSharp. And instead of registering my deserializer as a handler with the RestClient, which would have required my deserializer to handle ALL classes, I just invoked it inside my API class's Execute(Of T) method, for just the single case where T is the troublesome class.
The Execute(Of T) method:
Public Function Execute(Of T As New)(request As RestRequest) As T
Dim client = New RestClient()
' set up client with authenticator
client.BaseUrl = BaseURL
If String.IsNullOrEmpty(_sessionID) Then
client.Authenticator = New HttpBasicAuthenticator(_apikey, "")
Else
client.Authenticator = New HttpBasicAuthenticator(_apikey, _sessionID)
End If
' used on every request
Dim response = client.Execute(Of T)(request)
' Check for exceptions or bad status code
If response.ErrorException IsNot Nothing Then
Throw response.ErrorException
ElseIf response.StatusCode > 299 Then
If response.Content.StartsWith("{""error""") Then
Throw New Exception(String.Format("Status {0} {1} : {2}", response.StatusCode, response.StatusDescription, response.Content))
Else
Throw New HttpException(response.StatusCode, response.StatusDescription)
End If
End If
' Handle troublesome class
If GetType(T).Equals(GetType(mediaGallery)) Then
Dim fjs As New fotoliaJSONDeSerializer
response.Data = fjs.Deserialize(Of T)(response)
End If
Return response.Data
End Function
The deserializer class:
''' <summary>
''' specific to the FotoliaAPI.mediaGallery we actually want to handle
''' </summary>
''' <param name="response"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function DeserializeMediaLibrary(response As IRestResponse) As FotoliaAPI.mediaGallery
Dim result As New FotoliaAPI.mediaGallery
' turn to an iDictionary so we can readily enumerate keys
Dim j As IDictionary(Of String, Object) = CType(SimpleJSON.SimpleJson.DeserializeObject(response.Content), IDictionary(Of String, Object))
For Each key In j.Keys
' this top level key is a direct property
If key = "nb_results" Then
result.nb_results = j(key)
Else
' all other keys become members of the list.
' Turn the value back to a string, then feed it back into SimpleJson to deserialize to the strongly typed subclass.
result.media.Add( _
SimpleJSON.SimpleJson.DeserializeObject(Of FotoliaAPI.mediaGalleryData)( _
j(key).ToString))
End If
Next
Return result
End Function
' required but unimportant properties of IDeserializer
Public Property DateFormat As String Implements Deserializers.IDeserializer.DateFormat
Public Property [Namespace] As String Implements Deserializers.IDeserializer.Namespace
Public Property RootElement As String Implements Deserializers.IDeserializer.RootElement
End Class