2

How can I take just the first element from a Json?

//take result back
    void HandleIncomingMessage(object sender, PEventArgs e)
    {
        RetMessage += e.Result;
        //here can not deserialize correct
        var deserialized_message = JsonConvert.DeserializeObject<Message>(RetMessage);
    }

Here I am doing the deserialize but because it`s taking the entire object can not parse it correct.

I need just JSON.[0]

Edit: Raw Json :

 [{"unique_id":55,"action_name":"INSERT","start_date":"2018-06-11T16:00:00","end_date":"2018-06-11T17:00:00"},"1sddsd","my_channel"]
Alexandra Damaschin
  • 761
  • 3
  • 13
  • 28

3 Answers3

9

Deserialize to List<dynamic>, then read the properties of its first element.

//using Newtonsoft.Json;
var input = @"[{""unique_id"":55,""action_name"":""INSERT"",""start_date"":""2018-06-11T16:00:00"",""end_date"":""2018-06-11T17:00:00""},""1sddsd"",""my_channel""]";
var output = JsonConvert.DeserializeObject<List<dynamic>>(input);
Console.WriteLine(output[0].unique_id);

Output:

55

DotNetFiddle

John Wu
  • 50,556
  • 8
  • 44
  • 80
1

How about getting json string and using JSON.net

//first create object from json
JObject jObject = JObject.Parse(jsonString);
//read unique value        
string jUniqueId = jObject["unique_id"];
//or
string firstObject = jObject[0];
aditya
  • 57
  • 1
  • 8
-3

the solution is for static,

JObject obj= JObject.Parse(here pass the JSON);
  string id=  JSON[0]["unique_id"],
  string name=  JSON[0]["action_name"],
  string sdate=  JSON[0]["start_date"],
  string edate=  JSON[0]["end_date"]

dynamic means pass i instead of 0.

Mohan Srinivas
  • 302
  • 3
  • 13