Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access element from jArray with Linq

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"

like image 545
nmrlqa4 Avatar asked Jan 04 '23 16:01

nmrlqa4


1 Answers

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>();
like image 100
Aleks Andreev Avatar answered Jan 13 '23 15:01

Aleks Andreev