簡體   English   中英

從 C# 中的 JSON 對象獲取值

[英]Get value from JSON object in c#

我從一個 url 得到 JSON 響應,我在jObj2使用以下代碼捕獲它

dynamic jObj2 = JsonConvert.DeserializeObject(resultCheck.Content.ReadAsStringAsync().Result);
Response.Write("<p>"+jObj2+"<p>");

輸出是:

{
    "method":"check",
    "trace":"1234/12345/123456f5",
    "order":{
        "ref":"2910730E3E90D40F59BC9B738E71EF7AD9DF679C93D34EAEADA6775216F12C13",
        "cartid":"1723873570174343",
        "test":1,
        "amount":"30.00",
        "currency":"USD",
        "description":"Descsdaff",
        "status":{
            "code":3,
            "text":"Paid"
        },
        "transaction":{
            "ref":"019463997038",
            "type":"sale",
            "class":"ECom",
            "status":"A",
            "code":"919514",
            "message":"Authorised"
        },
        "card":{
            "type":"Visa Credit",
            "last4":"0002",
            "expiry":{
                "month":3,
                "year":2017
            }
        },
        "customer":{
            "email":"email@email.com",
            "name":{
                "forenames":"James",
                "surname":"Senior"
            },
            "address":{
                "line1":"Denvour",
                "city":"Denvour",
                "country":"US"
            }
        }
    } }

我如何訪問單個值

carid code ref ...

我試過下面的代碼,但它給了我錯誤

var jsonData2 = (JObject)JsonConvert.DeserializeObject(resultCheck.Content.ReadAsStringAsync().Result);
    
Response.Write("<br> jsonData2['order']['description'].ToString() " + jsonData2["order"]["url"].ToString())

錯誤信息

  Object reference not set to an instance of an object. Description: An
 unhandled exception occurred during the execution of the current web
 request. Please review the stack trace for more information about the
 error and where it originated in the code.
 
 Exception Details: System.NullReferenceException: Object reference not
 set to an instance of an object.
 
 Source Error:
 
 
 Line 65:                 Response.Write("<br>"); Line 66:             
 Response.Write("<br>"); Line 67:                 Response.Write("<br>
 jsonData2['order']['description'].ToString() " +
 jsonData2["order"]["description"].ToString()); Line 68:  Line 69:            
 }

我如何從 json 對象訪問單個值

還沒有嘗試過,但我認為,這是最相對的答案

https://stackoverflow.com/a/4749755/5458824

這可能有助於獲得所需的輸出

JToken token = JObject.Parse(JsonConvert.DeserializeObject(resultCheck.Content.ReadAsStringAsync().Result));
Response.Write("<br> token.SelectToken("description") " + token.SelectToken("description"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM