Sarotobi
Sarotobi

Reputation: 831

Getting the key value from a JSON object

I am passing an object to a C# winform application via socketIO i manage to get the data, but having trouble getting the key value from the object, so far below is my code to capture the data from the socket server.

socket.On("traverseLeft", (data) =>
    {
        Invoke(new Action(() =>
        {

           MessageBox.Show(data.ToString());

        }));

    });

So my output is below, what I need to get is the interactive_link's value which is "sub", how can I achieve this on C#?

{  
   "msg":{  
      "interactive_link":"sub"
   }
}

Upvotes: 1

Views: 11819

Answers (4)

Mehdi Isaloo
Mehdi Isaloo

Reputation: 183

If your data has a defined structure, you can use a Strongly-Typed manner. So you should define your classes first:

public class Msg
{
    public string interactive_link { get; set; }
}

public class DataObject
{
    public Msg msg { get; set; }
}

And the parse your JSON result to the defined object:

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<DataObject>(data);

Upvotes: 1

G.Dimov
G.Dimov

Reputation: 2393

First, download the Newtonsoft NuGet package: Newtonsoft.Json from NuGet.

Then create the following classes:

public class RootObject
{
    [JsonProperty("msg")]
    public Message Message { get; set; }
}

public class Message
{
    [JsonProperty("interactive_link")]
    public string InteractiveLink { get; set; }
}

And finally do this:

var inputObj = JsonConvert.DeserializeObject<RootObject>(data);
var message = inputObj.Message.InteractiveLink;
MessageBox.Show(message);

Hope this helps.

Upvotes: 5

Krishna Varma
Krishna Varma

Reputation: 4260

You can also use JObject to read the properties

JObject obj = JObject.Parse(json);
Console.WriteLine(obj["msg"]["interactive_link"]);

Upvotes: 4

Reyan Chougle
Reyan Chougle

Reputation: 5321

You can create the model class as per your JSON response. You can create it online using http://json2csharp.com/

public class Msg
{
    public string interactive_link { get; set; }
}

public class MyJson
{
    public Msg msg { get; set; }
}

And then deserialize your json to this class using Newtonsoft.Json(nuget).

var myJson = JsonConvert.DeserializeObject<MyJson>(json); 

And then access your data

var interactiveLink = myJson.msg.interactive_link;

Upvotes: 2

Related Questions