Decoding JSON data in a Webmethod from an AJAX call

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!

Answer №1

After some investigation, I discovered the issue at hand. It turns out that the code I initially had was meant for deserializing an array of objects, but the JSON object being passed was not in the correct format, causing an error to occur. To rectify this, I removed the loop and made the following replacement:

          <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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Insert a new store into an existing IndexedDB database that is already open

After opening and passing the onupgradeneeded event in IndexedDB, is there a way to create a new store? My attempted code: var store = db.createObjectStore('blah', {keyPath: "id", autoIncrement:true}); This resulted in the following error mess ...

What is the best way to dynamically insert a new row into a table, with each row containing a table heading and column?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tbl" class="tbl1"> <tr> <th> mobileno </th> <td class='mo' id="mo_0"> </td> ...

Is there a way to use lodash to convert an array into an object?

Below is an array that I am working with: const arr = [ 'type=A', 'day=45' ]; const trans = { 'type': 'A', 'day': 45 } I would appreciate it if you could suggest the simplest and most efficient method to ...

Managing the state of forms using NGRX and @Effects

After submitting a form and triggering an action that is caught by an effect for an http call, I am curious about how to handle the following scenarios upon completion or failure: Display a success message once the action finishes Reset all fields for fu ...

Synchronous async routes in Node Express

My express server requires fetching data from multiple external sources for each request, with the logic separated into various routers (some of which are not under my control). These routers operate independently, eliminating the need for one to wait on ...

Transforming Excel data into nested Json structure with child elements organized as arrays

I'm attempting to utilize Python to convert Excel data into nested JSON, where repetitive values are placed into an array of elements. For example, given the CSV structure: Manufacturer,oilType,viscosity shell,superOil,1ova shell,superOil,2ova shell, ...

When the mouse hovers over DIV2, the background image of DIV1 will be replaced

I have a full-screen background div with the ID #background-change. Within that full-screen background, I have 3 Divs named .fullscreen-column-1, .fullscreen-column-2, etc. My goal is to change the background image of #background-change when the mouseove ...

Issues with MC-Cordova-Plugin on Ionic and Angular Setup

Recently, I integrated a plugin for Ionic from this repository: https://github.com/salesforce-marketingcloud/MC-Cordova-Plugin After successfully configuring it for iOS, I encountered difficulties on Android where the plugin seems to be non-existent. It ...

Where can I locate the list of events supported by CKEditor 4?

Looking for the list of available events I attempted to locate the event list in the official documentation, but unfortunately came up short. I resorted to searching through the source code using .fire("/s+") to identify all available events. However, thi ...

problem with maximum width in Internet Explorer 8

Struggling with a compatibility issue in IE8. Here's my HTML code - Test in any browser and then try in IE8 jsfiddle.net/G2C33/ The desired output should be like this The problem is that the max-width property doesn't work in IE8. Note: Test ...

Anticipate commitments during onbeforeunload

Is there a way to trigger a $http.get request when the page is closed? I encountered an issue where promises cannot be resolved because once the final method returns, the page is destroyed. The challenge lies in the fact that onbeforeunload does not wait ...

Meteor JS: How can I effectively manage the state of a unique template?

I'm currently delving into the realms of Session and reactive data sources within the Meteor JS framework. They prove to be quite useful for managing global UI states. However, I've encountered a challenge in scoping them to a specific instance o ...

String Representation of Android View IDs

As I work on creating a Class that will populate my layouts with data from a JSON Schema, I am encountering a challenge. The JSON includes definitions such as { type: "checkbox", label: "Label text", value: true, id: "liquids" }. While rendering the UI is ...

Using React to update an existing array of objects with a new array containing objects of the same type

My issue involves an array in a class's state, referred to as A. A is populated with objects of type B through the function f in the constructor. Subsequently, I create a new array of objects of type B called C using f and new data. Upon setting the s ...

What is the best way to include a dialog div within a form tag?

I am facing an issue with a JQuery dialog on my webpage. The data entered into the dialog seems to get lost because the dialog is placed outside the form tag. Here is how it appears: https://i.stack.imgur.com/fnb07.png So far, I have attempted this soluti ...

How can I make a recently added row clickable in an HTML table?

I have a table where each row is given the class ".clickablerow". I've set up an onclick function so that when a row is clicked, a dialog box appears allowing me to insert text above or below as a new row. The issue I'm facing is that even though ...

What is the proper way to incorporate a randomly generated number from a variable into a JSON index retrieval?

For my project, I am working on a slideshow that pulls image URLs from a JSON file containing 100 images. However, I only want to display 5 random images from the JSON each time the page loads. The HTML is styled within a style tag in an EJS file that is l ...

Guide on adding data into a database through URL parameters using the CodeIgniter framework

Currently, I am utilizing CodeIgniter to retrieve JSON items from a database and insert them. Initially, I followed the tutorial on the CodeIgniter website which involved using a form to send data to the database, and everything functioned correctly. Howev ...

Ways to retrieve specific data from a JSON object

With the help of NewtonSoft, I successfully convert JSON using the following code snippet: var jtoken = JObject.Parse(stringStuff); Console.WriteLine(jtoken.ToString()); The result is as follows: { "data": { "user": { " ...

Express.js encountered a FetchError due to receiving an invalid JSON response body from https://api.twitter.com

I am currently working on a project that involves getting the tweet id as form input and using the Twitter API to retrieve data about that specific tweet. However, I have encountered an issue where the JSON data is not being returned properly. router.post( ...