在asp.net应用程序中接收数据

时间:2013-02-01 08:11:20

标签: asp.net json http

我向api发出一个http请求,然后向我的asp.net应用程序发送一些响应。

发送的数据格式为

{
    "deliveryInfoNotification": {
        "deliveryInfo": {
            "address": "14075550100",
            "code": "0",
            "createdDateTime": "2011-05-12T00:55:25.313Z",
            "deliveryStatus": "DeliveredToNetwork",
            "direction": "outbound",
            "message": "Hello world",
            "messageId": "3e5caf2782cb2eb310878b03efec5083",
            "parts": "1",
            "senderAddress": "16575550100",
            "sentDateTime": "2011-05-12T00:55:34.359Z"
        }
    }
}

如果收到那些数据,我怎样才能通过我的asp.net应用程序接收和解析这些数据?

1 个答案:

答案 0 :(得分:0)

要在ASP.NET中处理JSON,您可以使用Web.Script.Serialization.JavaScriptSerializer(添加对System.Web.Extensions的引用)。将.DeserializeObject()返回的对象转换为Generic.Dictionary以使用它。

Dim json As String = String.Concat(
   "{",
       """deliveryInfoNotification"": {",
           """deliveryInfo"": {",
               """address"": ""14075550100"",",
               """code"": ""0"",",
               """createdDateTime"": ""2011-05-12T00:55:25.313Z"",",
               """deliveryStatus"": ""DeliveredToNetwork"",",
               """direction"": ""outbound"",",
               """message"": ""Hello world"",",
               """messageId"": ""3e5caf2782cb2eb310878b03efec5083"",",
               """parts"": ""1"",",
               """senderAddress"": ""16575550100"",",
               """sentDateTime"": ""2011-05-12T00:55:34.359Z""",
           "}",
       "}",
   "}")

Dim serializer As New Web.Script.Serialization.JavaScriptSerializer,
    jsonObject As System.Collections.Generic.Dictionary(Of String, Object) =
        DirectCast(serializer.DeserializeObject(json), System.Collections.Generic.Dictionary(Of String, Object))

If jsonObject.Count > 0 _
    AndAlso jsonObject.ContainsKey("deliveryInfoNotification") _
    AndAlso jsonObject("deliveryInfoNotification").ContainsKey("deliveryInfo") Then

    Dim deliveryInfo As System.Collections.Generic.Dictionary(Of String, Object) = jsonObject("deliveryInfoNotification")("deliveryInfo"),
        address As String = deliveryInfo("address"),
        code As String = deliveryInfo("code"),
        createdDateTime As String = deliveryInfo("createdDateTime"),
        deliveryStatus As String = deliveryInfo("deliveryStatus"),
        direction As String = deliveryInfo("direction"),
        message As String = deliveryInfo("message"),
        messageId As String = deliveryInfo("messageId"),
        parts As String = deliveryInfo("parts"),
        senderAddress As String = deliveryInfo("senderAddress"),
        sentDateTime As String = deliveryInfo("sentDateTime")

End If