在vb.net中获取JSON对象的值 [英] Getting Values of a JSON Object in vb.net

查看:714
本文介绍了在vb.net中获取JSON对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已编辑

在vb.net中获取JSON对象的值时,我陷入了困境.我的JSON请求发布的数据如下所示:

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对象外观

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

上述请求在vb.net中返回一个对象

The above request returns an object in vb.net

VB代码:

<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?

推荐答案

至少一个问题不使用Option Strict On.错误代码:

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)

如果打开Option Strict,则由于JsonConvert.DeserializeObject采用字符串参数而无法编译.我不确定为什么异常(现在已删除图像)似乎来自VB而非Newtonsoft,但这无济于事.

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.

适用于修改#9

提及字典的错误似乎具有误导性,并且可能与内部属性的收集有关(很多时候json可以反序列化为Dictionary(Of String,String).给定json发布(带有数据):

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"
    }
  }
}

实际上有3个类:ClientsPersonalInfo和数据,ClientsData是包含该类的一个类,在以前的编辑中还包括ClientsVehicleInfo类.

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.

但是还有一个由封闭的{...}表示的类.可以为您创建类的机器人将其命名为ExampleRootObject.在这种情况下,我将其称为ClientContainer.

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.

这有效:

' 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

要反序列化数据(您可能需要对其进行调整以供Web使用,Shared在我看来似乎不正确):

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似乎是不需要的层.容器可以直接容纳其他两个对象. 如果是用于保存多个客户端的信息,则您将在json中使用密钥代替"ClientsData":(例如"ziggy":{}, "zacky":{}, "zoey":{}.

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":{}.

输出:

Ziggy Le Strange

Ziggy Le Strange

由于根据评论,车辆信息是交易的一部分,因此您可以将其更改为返回同时包含个人信息和车辆信息的ClientsData:

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. 打开Option Strict
  2. 不输入框参数或返回As Object,它们失去了某些含义.
  3. 请记住,json中最外面的花括号表示容器对象
  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.

这篇关于在vb.net中获取JSON对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆