猿问

从 C# 中的 json 文件访问单个值

我的 json 文件看起来像这样


{

lab :[

{

    "name": "blah",

    "branch": "root",

    "buildno": "2019"

}]

}

因此,我需要访问 buildno (2019) 的值并将其分配给我程序中的一个变量。


这是我的课


public class lab

{

    public string name { get; set; }

    public string branch { get; set; }

    public string buildno { get; set; }

}

我使用 Newtonsoft.json 尝试了这种方法


        using (StreamReader r = new StreamReader(@"ba.json"))

        {

            string json2 = r.ReadToEnd();

            lab item = JsonConvert.DeserializeObject<lab>(json2);

            Console.WriteLine(item.buildno);

        }

但是我没有得到任何输出!!!只有空白屏幕。


DIEA
浏览 195回答 3
3回答

慕码人8056858

您可以使用以下函数从 json 获取单个值。JObject.Parse()只需将任何 API 返回的 json(如果您正在使用)作为参数传递给 Parse 函数并获取如下值:// parsing the json returned by OneSignal Push API&nbsp;dynamic json = JObject.Parse(responseContent);int noOfRecipients = json.recipients;我使用 OneSingal API 发送推送通知,并在点击他们的 API 时返回一个 json 对象。这里的“收件人”基本上是 json 中返回的键。希望这有助于某人。

素胚勾勒不出你

首先你创建一个json对象var lab = JSON.stringify({&nbsp; &nbsp; "name": "blah",&nbsp; &nbsp; &nbsp; &nbsp; "branch": "root",&nbsp; &nbsp; &nbsp; &nbsp; "buildno": "2019"&nbsp; &nbsp; });然后你可以像这样得到这个json对象dynamic model = JsonConvert.DeserializeObject(lab);然后你会得到像这样的价值&nbsp; lab l = new lab();&nbsp; l.buildno =&nbsp; model.buildno;希望这对你有帮助。
随时随地看视频慕课网APP
我要回答