Reputation: 679
I want to get the first or default element of jArray into an object
{[
{
"timex": "XXXX-08-25",
"type": "date",
"value": "2016-08-25"
},
{
"timex": "XXXX-08-25",
"type": "date",
"value": "2017-08-25"
}
]}
(This array can be different by the next call) How can I get the value of "value" from the first element in an object with linq? This: "2016-08-25"
Upvotes: 4
Views: 15278
Reputation: 273
Try this i think this is answer what you want!
var myData = {[
{
"timex": "XXXX-08-25",
"type": "date",
"value": "2016-08-25"
},
{
"timex": "XXXX-08-25",
"type": "date",
"value": "2017-08-25"
}
]}
List<MyDataList> _myDataList = new List<MyDataList>();
foreach(var item in myData)
{
MyDataList _myDataListObject = new MyDataList();
Dictionary<string, object> desirializedJsonObject = JsonConvert.DeserializeObject<Dictionary<string, object>>(item.ToString());
myDataListObject.timex = Convert.ToString(desirializedJsonObject["timex"]);
myDataListObject.type= Convert.ToString(desirializedJsonObject["type"]);
myDataListObject.value = Convert.ToString(desirializedJsonObject["value"]);
myDataList.Add(myDataListObject);
}
//Get first records data
MyDataList _myData = myDataList.FirstOrDefault();
//Your class to get data
public class MyDataList
{
public string timex {get; set;}
public string type {get; set;}
public string value {get; set;}
}
Upvotes: 3
Reputation: 7054
Your json seems not valid, because it's starts with "{[". On valid JSON input you can use this code:
var input = "[ { \"timex\": \"XXXX-08-25\",\r\n \"type\": \"date\",\r\n \"va2lue\": \"2016-08-25\"\r\n },\r\n {\r\n \"timex\": \"XXXX-08-25\",\r\n \"type\": \"date\",\r\n \"value\": \"2017-08-25\"\r\n }\r\n]";
var jArray = JArray.Parse(input);
var result = jArray.FirstOrDefault()?["value"]?.Value<DateTime>();
Upvotes: 8