我有一个用javascript构建的JSON对象,我想将一个ajax请求传递给VB.Net WebMethod并反序列化它。我使用Newtonsoft JSON反序列化对象。似乎对象被传递但当我尝试将其反序列化为对象时,我收到此错误:Error converting value "myid" to type 'AnID.RF.MyIDProfile'.
以下是我正在使用的javascript代码:
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);
}
})
}
这是服务器端代码:
<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
End Namespace
如果我使用SelectToken(&#34; profile.myid&#34;),我可以毫无问题地获得价值。我不确定我做错了什么导致了这个错误。任何人都可以看一看吗?
答案 0 :(得分:1)
我弄清楚出了什么问题。我的代码用于反序列化一个对象数组,并且传入的json对象不是导致错误的对象数组。我删除了循环并将其替换为:
<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 oDetail As RF.MyIDProfile = jO("profile").ToObject(Of RF.MyIDProfile)()
Dim sTest2 As String = oDetail.myid
Catch ex As Exception
sMessage = "e"
End Try
Return sMessage
End Function