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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With