Accessing a single value from a json file in c#

老子叫甜甜 提交于 2021-02-19 04:26:07

问题


My json file looks something like this

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

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

This is my class

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

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.


回答1:


You can make use of the following function to get a single value from json.

JObject.Parse()

Just pass the json returned by any of API's (if you are using) as a parameter to Parse function and get the value as follows:

// parsing the json returned by OneSignal Push API 
dynamic json = JObject.Parse(responseContent);
int noOfRecipients = json.recipients;

I was using OneSingal API to send push notifications and on hitting their API it returned a json object. And here 'recipients' was basically a key returned in the json. Hope this helps someone.




回答2:


jsong structure , given by you

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

its not valid json structure , it should be like this

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

and then you C# class structure for that is

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.


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

Example :

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);



回答3:


First of all you create a json object by

var lab = JSON.stringify({
    "name": "blah",
        "branch": "root",
        "buildno": "2019"
    });

then you can get this json object like this

dynamic model = JsonConvert.DeserializeObject(lab);

then you get value like as

  lab l = new lab();
  l.buildno =  model.buildno;

Hopefully this help for you.



来源:https://stackoverflow.com/questions/50480417/accessing-a-single-value-from-a-json-file-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!