Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value by key from JObject?

Tags:

json

c#

I have a JObject like this:

{   "@STARTDATE": "'2016-02-17 00:00:00.000'",   "@ENDDATE": "'2016-02-18 23:59:00.000'" } 

I want to get @STARTDATE and @ENDDATE value from JObject.


This is a sample code that I've tried to do the task:

JObject json = JObject.Parse("{\"@STARTDATE\": \"'2016-02-17 00:00:00.000'\",\"@ENDDATE\": \"'2016-02-18 23:59:00.000'\"}"); var key = "@STARTDATE";  var value = GetJArrayValue(json, key);  private string GetJArrayValue(JObject yourJArray, JToken key) {     string value = "";     foreach (JToken item in yourJArray.Children())     {         var itemProperties = item.Children<JProperty>();         //If the property name is equal to key, we get the value         var myElement = itemProperties.FirstOrDefault(x => x.Name == key.ToString());         value = myElement.Value.ToString(); //It run into an exception here because myElement is null         break;     }     return value; } 

Note: The code above cannot get the value by key from JObject.


Could you help me to find a way to get the value by key from JObject?

like image 372
Trind 07 Avatar asked May 27 '16 09:05

Trind 07


People also ask

What is the difference between JToken and JObject?

JToken is the base class for all JSON elements. You should just use the Parse method for the type of element you expect to have in the string. If you don't know what it is, use JToken, and then you'll be able to down cast it to JObject, JArray, etc. In this case you always expect a JObject, so use that.

What is JObject parse in C#?

JObject class has parse method; it parses the JSON string and converts it into a Key-value dictionary object. In the following example, I have used “JObject. Parse” method and retrieved data using key. string jsonData = @"{ 'FirstName':'Jignesh', 'LastName':'Trivedi' }"; var details = JObject.


2 Answers

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }"; var fdate = JObject.Parse(json)["@STARTDATE"]; 
like image 70
Amit Kumar Ghosh Avatar answered Oct 11 '22 10:10

Amit Kumar Ghosh


You can also get the value of an item in the jObject like this:

JToken value; if (json.TryGetValue(key, out value)) {    DoSomething(value); } 
like image 34
MarkB Avatar answered Oct 11 '22 10:10

MarkB