从C#中的json文件访问单个值 [英] Accessing a single value from a json file in c#

查看:79
本文介绍了从C#中的json文件访问单个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json文件看起来像这样

My json file looks something like this

{
lab :[
{
    "name": "blah",
    "branch": "root",
    "buildno": "2019"
}]
}

所以,我需要访问buildno(2019)的值并将其确定为程序中的变量.

so, i need to access the value of the buildno (2019) and assaign it to a variable in my program.

这是我的课程

public class lab
{
    public string name { get; set; }
    public string branch { get; set; }
    public string buildno { get; set; }
}

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

I tried this method using Newtonsoft.json

        using (StreamReader r = new StreamReader(@"ba.json"))
        {
            string json2 = r.ReadToEnd();
            lab item = JsonConvert.DeserializeObject<lab>(json2);
            Console.WriteLine(item.buildno);
        }

但是我没有得到任何输出!!!只有黑屏.

But I'm not getting any output!!! only blank screen.

推荐答案

jsong结构,由您提供

jsong structure , given by you

{
lab :[
{
    "name": "blah",
    "branch": "root",
    "buildno": "2019"
}
}

无效的json结构,应该是这样

its not valid json structure , it should be like this

{
lab :[
{
    "name": "blah",
    "branch": "root",
    "buildno": "2019"
}]
}

然后您的C#类结构是

public class Lab
{
    public string name { get; set; }
    public string branch { get; set; }
    public string buildno { get; set; }
}

public class RootObject
{
    public List<Lab> lab { get; set; }
}

如果执行此操作,则下面的代码将起作用,或者您尝试的代码将起作用.

if you do that then below code will work or code you are trying will work.

使用Deserialize/serialize将您的json转换为.net对象类型:使用Newtonsoft库:序列化和反序列化JSON

make use of Deserialize/serialize to convert you json in .net object type :make use of Newtonsoft library : Serializing and Deserializing JSON

示例:

string json = @"{
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine( account.Email);

这篇关于从C#中的json文件访问单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆