2017-07-28 51 views
0

訪問元素我想jArray的第一或默認元素爲對象如何從jArray使用LINQ

{[ 
    { 
    "timex": "XXXX-08-25", 
    "type": "date", 
    "value": "2016-08-25" 
    }, 
    { 
    "timex": "XXXX-08-25", 
    "type": "date", 
    "value": "2017-08-25" 
    } 
]} 

(該陣列可以是通過下一次調用不同),我怎樣才能得到的值linq對象中的第一個元素的「值」?這個:「2016-08-25」

回答

0

你的json似乎無效,因爲它是以「{[」開頭的。在有效的JSON輸入您可以使用此代碼:

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

試試這個,我認爲這是回答你要的東西!

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