Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a single value from a json file in c#

Tags:

json

c#

c#-4.0

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.

like image 540
Abhishek K Suresh Avatar asked Oct 15 '25 12:10

Abhishek K Suresh


2 Answers

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.

like image 139
Harry .Naeem Avatar answered Oct 18 '25 01:10

Harry .Naeem


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': '[email protected]',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine( account.Email);
like image 34
Pranay Rana Avatar answered Oct 18 '25 02:10

Pranay Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!