4

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"

2 Answers 2

7

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>();
3

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;}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.