Search code examples
jsonvb.netwebmethod

Getting Values of a JSON Object in vb.net


EDITED:

I got stuck while getting value of a JSON object in vb.net. My JSON request posts data like given below:

function submitEmail() {

        var ClientsPersonalInfo = {
            FullName: $("#FullName").val(),
            PhoneNumber: $("#PhoneNumber").val(),
            EmailAddress: $("#EmailAddress").val(),
            DOB: $("#DOB").val(),
            Occupation: $("#Occupation").val(),
            NINumber: $("#NINumber").val(),
            FullAddress: $("#FullAddress").val()
        }

        var ClientsData = {};
        ClientsData.ClientsPersonalInfo = ClientsPersonalInfo;

        var d = '{"ClientsData":' + JSON.stringify(ClientsData) + '}'

        $.ajax({
            type: "POST",
            url: "add-new-client.aspx/SubmitEmail",
            data: d,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response)
            },
            failure: function (msg) {
                alert(msg);
            }
        });
}

JSON Object Looks Like

{
"ClientsPersonalInfo": {
    "FullName": "",
    "PhoneNumber": "",
    "EmailAddress": "",
    "DOB": "",
    "Occupation": "",
    "NINumber": "",
    "FullAddress": ""
    }
}

The above request returns an object in vb.net

VB Code:

<WebMethod()> _
    Public Shared Function SubmitEmail(ByVal ClientsPersonalInfo As Object) As String

        // What to do next to get object "ClientsPersonalInfo"
        // I want to access properties of the object like
        //Dim name As String = ClientsPersonalInfo.FullName

        Return "Successfully Converted."

    End Function

No I want to get values of this object and needs to append in a table. Please guide me how to get values of the above object?


Solution

  • At least one problem is not using Option Strict On. The code at fault:

    Shared Function SubmitEmail(ByVal ClientData As Object) As String
        Dim obj = JsonConvert.DeserializeObject(Of NewClientData)(ClientData)
    

    If you turn on Option Strict that will not compile because JsonConvert.DeserializeObject takes a string argument. I am not sure why the exception (image now removed) seems to come from VB rather than Newtonsoft, but that isnt helping.

    Your deserialized object will also just disappear when it goes out of scope when the method ends.


    Applicable to Edit #9

    The error mentioning a Dictionary seems misleading and probably something internal relating to how the properties are collected (many times json can be deserialized to a Dictionary(Of String, String). Given the json posted (with data):

    {
    "ClientsData": {
        "ClientsPersonalInfo": {
            "FullName": "Ziggy Le Strange",
            "PhoneNumber": "505050",
            "EmailAddress": "ziggy@foobar.com",
            "DOB": "",
            "Occupation": "Freelancer",
            "NINumber": "7",
            "FullAddress": "123 Easy street"
        }
      }
    }
    

    There are actually 3 classes: ClientsPersonalInfo with the data, ClientsData which is a class containing that one and in previous edits also included a ClientsVehicleInfo class.

    But there is yet another class represented by the enclosing {...}. The robots who can create the classes for you name it Example or RootObject. In this case, I would call it ClientContainer.

    This works:

    ' the outermost {}
    Public Class ClientContainer
        Public Property ClientsData As ClientsData
    End Class
    
    Public Class ClientsPersonalInfo
        Public Property FullName As String
        Public Property PhoneNumber As String
        Public Property EmailAddress As String
        Public Property DOB As String
        Public Property Occupation As String
        Public Property NINumber As String
        Public Property FullAddress As String
    End Class
    
    Public Class ClientsData
        Public Property ClientsPersonalInfo As ClientsPersonalInfo 
        Public Property ClientsVehicleInfo As ClientsVehicleInfo
    End Class
    
    Public Class ClientsVehicleInfo
        ' whatever it is supposed to hold
    End Class
    

    To deserialize the data (you may have to adapt it for web use, Shared seems incorrect to me):

    ' pass in the json AS STRING
    ' returns JUST the ClientsPersonalInfo
    Public Function GetClientData(jsonData As String) As ClientsPersonalInfo
    
       ' you must use the container class 
        Dim client = JsonConvert.DeserializeObject(Of ClientContainer)(jsonData )
    
        ' TEST:
        Console.WriteLine(client.ClientsData.ClientsPersonalInfo.FullName)
    
        Return client.ClientsData.ClientsPersonalInfo
    
    End Function
    

    ClientsData seems to be an unneeded layer. The container could hold both of the other objects directly. If this is meant to hold info for more than one client, you would have keys in place of "ClientsData": in the json (e.g. "ziggy":{}, "zacky":{}, "zoey":{}.

    Output:

    Ziggy Le Strange

    Since, as per comment, that vehicle info is part of the deal, you can change it to return ClientsData which holds both the Personal and Vehicle info:

    Public Function GetClientData(jsonData As String) As ClientsData
    
       ' you must use the container class 
        Dim client = JsonConvert.DeserializeObject(Of ClientContainer)(jsonData )
    
        Return client.ClientsData
    
    1. Turn on Option Strict
    2. Dont box parameters or returns As Object, they loose some of their meaning.
    3. Keep in mind that the outermost braces in json represent a container object

    Also, storing a Date as string looks bad too.