I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization:
Error converting value "myid" to type 'AnID.RF.MyIDProfile'.
Below is the JavaScript code I have implemented:
function test() {
var testdata;
testdata = "{'data':{'ses':'','profile':{'myid':'myid','username':'User','firstName':'adf','lastName':'lastname','languagePreference':'en'}}}";
$.ajax({
type: "POST",
url: "default.aspx/Foo",
data: testdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function() {
},
success: function(data) {
if (data != "") {
alert(data.d);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
})
}
And here is the server-side code snippet:
<System.Web.Services.WebMethod()> _
Public Shared Function Foo(ByVal data As Object) As String
Dim jO As JObject = JObject.FromObject(data)
Dim sMessage As String = "y"
Try
Dim results As IList(Of JToken) = jO("profile").Children().ToList()
Dim searchResults As IList(Of RF.MyIDProfile) = New List(Of RF.MyIDProfile)()
For Each result As JToken In results
Dim searchResult As RF.MyIDProfile = JsonConvert.DeserializeObject(Of RF.MyIDProfile)(result.ToString())
searchResults.Add(searchResult)
Next
Dim stest As String = jO.SelectToken("profile.myid").ToString
Catch ex As Exception
sMessage = "e"
End Try
Return sMessage
End Function
Namespace RF
Public Class MyIDProfile
Private sMYID As String
Private sUSERName As String
Private sPrefix As String
Private sFirstName As String
Private sLastName As String
Private slanguagePreference As String
Public Property myid() As String
Get
Return sMYID
End Get
Set(ByVal value As String)
sMYID = value
End Set
End Property
Public Property username() As String
Get
Return sUSERName
End Get
Set(ByVal value As String)
sUSERName = value
End Set
End Property
Public Property firstName() As String
Get
Return sFirstName
End Get
Set(ByVal value As String)
sFirstName = value
End Set
End Property
Public Property lastName() As String
Get
Return sLastName
End Get
Set(ByVal value As String)
sLastName = value
End Set
End Property
Public Property languagePreference() As String
Get
Return slanguagePreference
End Get
Set(ByVal value As String)
slanguagePreference = value
End Set
End Property
End Class
Namespace
I am puzzled by the error message when trying to deserialize the object despite being able to retrieve the value using SelectToken("profile.myid"). Any insights on what might be causing this issue would be greatly appreciated. Thank you for your help!