簡體   English   中英

使用 Json.Z7FB58B61118DFE34058E05B86C 獲取 JSON 數組 C# 的值

[英]Get the value of a JSON Array C# using Json.Linq

我喜歡得到 JSON 數組的第一個值。

我的 JSON:

{
    "userlist": [
        {
            "id": 123,
            "name": "Max",
        }
    ],
}

我有的:

public int JSONId(string JSONstring)
        {
            JObject responseJSON = JObject.Parse(ResponseGETSearchForCorrectID);
            int id = (int)JArray.Parse(ResponseGETSearchForCorrectID).Children()["userlist"]["id"].First();

            return id;
        }

但我收到此錯誤:Newtonsoft.Json.JsonReaderException:'從 JsonReader 讀取 JArray 時出錯。 當前 JsonReader 項不是數組:StartObject。 路徑'',第 1 行,position 1。

我也試過:

int idPackage = responseJSON["userlist"]["id"].Values;

但也不起作用,因為我得到一個異常信息,這是一個數組。

我在這里做錯了什么? 有人解決了嗎?

謝謝你。

試試這個方法

int idPackage = responseJSON["userlist"][0]["id"].Value<int>();

由於 userliat 是一個數組,因此您必須通過索引訪問對象。

試試這個方法:

var obj = JsonConvert.DeserializeObject(str);
int id = obj.userlist[0].id;

暫無
暫無

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

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