Alexandra Damaschin
Alexandra Damaschin

Reputation: 840

Extract first element from JSON

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"]

Upvotes: 2

Views: 16481

Answers (3)

John Wu
John Wu

Reputation: 52280

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

Upvotes: 9

Mohan Srinivas
Mohan Srinivas

Reputation: 312

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.

Upvotes: -3

aditya
aditya

Reputation: 57

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

Upvotes: 1

Related Questions