Home Ask Login Register

Developers Planet

Your answer is one click away!

user174634 February 2016

Pass type as parameter to newtonsoft json deserialize

I have this working line of code

Public Shared Function JSONArrayToObject(source As String, result As Type) As Object
    Return JsonConvert.DeserializeObject(Of PAManufacturer())(source)
End Function

result is a type and I would like to replace PAManufacturer with GetType(result) or the equivalent.

I haven't been able to get around this problem. I could have a hundred of these deserialize methods but i'm sure I should be able to use the result variable somehow.


James Thorpe February 2016

You can use generic functions (of which DeserializeObject is one) for this:

Public Shared Function JSONArrayToObject(Of T)(source As String) As T()
    Return JsonConvert.DeserializeObject(Of T())(source)
End Function

Where you could call it as:

Dim arr as PAManufacturer() = JSONArrayToObject(Of PAManufacturer())(someSourceString)

Though if you get to that level, one wonders why you use a function at all, and not just have the code call JsonConvert.DeserializeObject directly.

Post Status

Asked in February 2016
Viewed 2,336 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life