1

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"
   }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sarotobi
  • 707
  • 1
  • 9
  • 28
  • 3
    you should use newtonsoft to parse json. https://www.newtonsoft.com/json check their site for code samples – mausinc Nov 13 '19 at 09:29
  • 3
    just search for any way of parsing json in C#... there are many ways and many examples – demo Nov 13 '19 at 09:30
  • 1
    Does this answer your question? [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – aloisdg Nov 13 '19 at 09:31

4 Answers4

4

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
G.Dimov
  • 2,173
  • 3
  • 15
  • 40
3

You can also use JObject to read the properties

JObject obj = JObject.Parse(json);
Console.WriteLine(obj["msg"]["interactive_link"]);
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25
2

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;
Reyan Chougle
  • 4,917
  • 2
  • 30
  • 57
1

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);
Mehdi Isaloo
  • 174
  • 1
  • 4