在 vb.net 中获取 JSON 对象的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33853014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Values of a JSON Object in vb.net
提问by Ahsan Khurshid
EDITED:
编辑:
I got stuck while getting value of a JSON object in vb.net. My JSON request posts data like given below:
我在 vb.net 中获取 JSON 对象的值时卡住了。我的 JSON 请求发布如下所示的数据:
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
JSON 对象看起来像
{
"ClientsPersonalInfo": {
"FullName": "",
"PhoneNumber": "",
"EmailAddress": "",
"DOB": "",
"Occupation": "",
"NINumber": "",
"FullAddress": ""
}
}
The above request returns an object in vb.net
上面的请求返回了 vb.net 中的一个对象
VB Code:
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?
不,我想获取此对象的值并需要附加到表中。请指导我如何获取上述对象的值?
采纳答案by ??ssa P?ngj?rdenlarp
At least one problem is not using Option Strict On. The code at fault:
至少有一个问题是不使用Option Strict On. 出错的代码:
Shared Function SubmitEmail(ByVal ClientData As Object) As String
Dim obj = JsonConvert.DeserializeObject(Of NewClientData)(ClientData)
If you turn on Option Strictthat will not compile because JsonConvert.DeserializeObjecttakes 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.
如果你打开Option Strict它不会编译,因为JsonConvert.DeserializeObject它需要一个字符串参数。我不确定为什么异常(图像现已删除)似乎来自 VB 而不是 Newtonsoft,但这无济于事。
Your deserialized object will also just disappear when it goes out of scope when the method ends.
您的反序列化对象在方法结束时超出范围时也会消失。
Applicable to Edit #9
适用于编辑#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):
提到字典的错误似乎具有误导性,并且可能与如何收集属性有关(很多时候 json 可以反序列化为字典(字符串,字符串)。鉴于发布的 json(带有数据):
{
"ClientsData": {
"ClientsPersonalInfo": {
"FullName": "Ziggy Le Strange",
"PhoneNumber": "505050",
"EmailAddress": "[email protected]",
"DOB": "",
"Occupation": "Freelancer",
"NINumber": "7",
"FullAddress": "123 Easy street"
}
}
}
There are actually 3 classes: ClientsPersonalInfowith the data, ClientsDatawhich is a class containing that one and in previous edits also included a ClientsVehicleInfoclass.
实际上有 3 个类:ClientsPersonalInfo数据ClientsData是一个包含该类的类,并且在之前的编辑中也包含了一个ClientsVehicleInfo类。
But there is yet another class represented by the enclosing {...}. The robots who can create the classes for you name it Exampleor RootObject. In this case, I would call it ClientContainer.
但是还有另一个类由封闭的{...}. 可以为您创建课程的机器人将其命名为Example或RootObject. 在这种情况下,我会称它为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, Sharedseems incorrect to me):
反序列化数据(您可能必须将其调整为网络使用,Shared对我来说似乎不正确):
' 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
ClientsDataseems to be an unneeded layer. The container could hold both of the other objects directly. Ifthis 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":{}.
ClientsData似乎是不需要的层。容器可以直接容纳其他两个对象。 如果这是为了保存多个客户端的信息,您将"ClientsData":在 json 中使用密钥(例如"ziggy":{}, "zacky":{}, "zoey":{}.
Output:
输出:
Ziggy Le Strange
Ziggy Le Strange
Since, as per comment, that vehicle info is part of the deal, you can change it to return ClientsDatawhich holds both the Personal and Vehicle info:
由于根据评论,车辆信息是交易的一部分,您可以将其更改为ClientsData包含个人和车辆信息的返回:
Public Function GetClientData(jsonData As String) As ClientsData
' you must use the container class
Dim client = JsonConvert.DeserializeObject(Of ClientContainer)(jsonData )
Return client.ClientsData
- Turn on
Option Strict - Dont box parameters or returns
As Object, they loose some of their meaning. - Keep in mind that the outermost braces in json represent a container object
- 打开
Option Strict - 不要框参数或返回
As Object,它们失去了一些意义。 - 请记住,json 中最外面的大括号代表一个容器对象
Also, storing a Date as string looks bad too.
此外,将日期存储为字符串看起来也很糟糕。
回答by HadiRj
First make sure your Json is in valid format using jsonlint
Then generate class base on it using jsonutils
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 ClientsVehicleInfo Public Property DrivingLicense As String Public Property VehicleMakeModel As String Public Property VehicleColour As String Public Property PolicyNumber As String Public Property TypeOfCover As String Public Property VehicleStoredIn As String End Class Public Class ClientsData Public Property ClientsPersonalInfo As ClientsPersonalInfo Public Property ClientsVehicleInfo As ClientsVehicleInfo End Class Public Class ClientData Public Property ClientsData As ClientsData End ClassUse Newtonsoft JSONto deserialize your Json into object(s) then you may simply access its properties value. (remember to add Json.net to your project using Manage NuGet Packages)
Imports Newtonsoft.Json Dim obj = JsonConvert.DeserializeObject(Of Dictionary(Of String, ClientsData))(yourJsonString)
首先使用jsonlint确保您的 Json 格式有效
然后使用jsonutils基于它生成类
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 ClientsVehicleInfo Public Property DrivingLicense As String Public Property VehicleMakeModel As String Public Property VehicleColour As String Public Property PolicyNumber As String Public Property TypeOfCover As String Public Property VehicleStoredIn As String End Class Public Class ClientsData Public Property ClientsPersonalInfo As ClientsPersonalInfo Public Property ClientsVehicleInfo As ClientsVehicleInfo End Class Public Class ClientData Public Property ClientsData As ClientsData End Class使用Newtonsoft JSON将您的 Json 反序列化为对象,然后您可以简单地访问其属性值。(记得使用 Manage NuGet Packages 将 Json.net 添加到您的项目中)
Imports Newtonsoft.Json Dim obj = JsonConvert.DeserializeObject(Of Dictionary(Of String, ClientsData))(yourJsonString)

