我是vb.Net的新手,我用Google搜索了这个,但没找到我要找的东西, 我的情况是我使用ajax将json发布到http处理程序,json看起来像:
[
{Id:1, view,:true , write:false},
{Id:2, view: true , write:true}, ..etc
]
发布部分工作正常,但我仍然坚持如何访问httphandler中的tree_data以及如何获取tree_data参数的所有属性的值。 通常我会以这种方式访问发布的值:
Dim tree_data = context.Request("tree_data") \\ This Returning Nothing here, I think this way is used when the data type is not json
我的Ajax代码:
var tree_data = getTreeData();
// alert(tree_data.length);
$.ajax({
url: "Profiles_SubmitPermissions.ashx",
type: "POST",
data: JSON.stringify(tree_data),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
alert(error)
}
}).done(function (data) {
CreateTree('ACTMNG');
});
http Handler中的代码:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Serialization
Public Class Profiles_SubmitPermissions
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
context.Response.Write("Hello World!")
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim connectionString As String = UserIdentity.ClientConfig.ConnectionString
'Get parameters
'I need to get access to tree_data json
'I need to access to json properties such as id, view , write
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
答案 0 :(得分:1)
Vb.Net版本是:
导入的库:
Imports System.Web.Script.Serialization
Imports System.IO
将从请求中获取json的部分代码:
Dim tree_data As String = Nothing
HttpContext.Current.Request.InputStream.Position = 0
Using inputStream As StreamReader = New StreamReader(HttpContext.Current.Request.InputStream)
tree_data = inputStream.ReadToEnd()
End Using
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer =
New System.Web.Script.Serialization.JavaScriptSerializer()
Dim permissions = jsonSerializer.Deserialize(Of List(Of Object))(tree_data)
解析json以提取值的部分代码,可能是这段代码可以用不同的方式编写,但这就是我使用的:
For Each obj In permissions
Dim id As Integer
Dim view As Boolean
Dim write As Boolean
For Each pair In obj // each object is a pair of key and value
If pair.Key.Equals("Id") Then
id = pair.Value
ElseIf pair.Key.Equals("view") Then
view = pair.Value
ElseIf pair.Key.Equals("write") Then
write = pair.Value
End If
Next
// Do something with the current id , view ,write parameters
Next