I have a JSON object passed into my REST API. I use a generic API Controller which specific API’s inherit. Using JSON.NET, I’m attempting to determine the basic type (String, Integer, Boolean, etc) of the JSON data. Here’s an example:
Public Overridable Function PostValue(<FromBody()> record As JObject)
For Each thing As KeyValuePair(Of String, JToken) In record
MsgBox(thing.Key & ": " & thing.Value.ToString & " (" & thing.Value.Type & ")")
Next
'do other stuff and return some other stuff...
End Function
Unfortunately, this is just returning string as the type for all of the JSON values. Is there a good method to parse the basic type of a JSON data member from the string value?
UPDATE
I understand that JSON, as Javascript, is always untyped – and I know that when JSON data is passed around, it’s always as a JSON string (and hence, typed string). I guess I was wondering if JSON.NET (or any other library for this matter) had a means to dynamically determine the basic types of the data stored within this JSON string. For example (note: I know that parseType doesn’t exist):
Json.ParseType("1") ' --> String
Json.ParseType(1) ' --> Integer
Json.ParseType("True") ' --> String
Json.ParseType(True) ' --> Boolean
Json.ParseType([1,2,3]) ' --> Array
'etc...
This is for a large part due to two factors.
First you are serializing data, not structure (types).
and Second, Javascript (and thus JSON) are type-less. [eg. alert(1.0 == ‘1.0’); will result in true).
In order to preserve type information you need to serialize the type information, and do something with it on the deserialization side.
example:
I would avoid trying to guess at the type. Just because you can convert the
idproperty value into an Int32 (via guessing) doesn’t mean that the next object’s id value will be an Int32. You must also be careful of values that contain numeric data in string format.. for example, international phone numbers: 011334998723 – if you were to convert that to an integer type, you’d lose the leading zero and completely change the meaning of the data.