I've got a question. I try to get value from JSON. JSON have been sent from server by socket. In Client I've got sth like this:
string data = null;
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine(data);
Console.ReadLine();
And in console I see :
{"player":0, "size":3}
How can I get value from this String ?
it is very simple. first download this nuget via Package Manager Console:
Install-Package Newtonsoft.Json -Version 11.0.2
then add this namespace: Newtonsoft.Json.Linq
JObject jObject = JObject.Parse(data);
int player = jObject["player"].Value<int>();
The easiest way to do this is to use Visual Studio: Copy the JSON text into the clipboard then select Edit | Paste Special | Paste JSON as classes. Rename the class as desired (for this example, call it Demo).
Newtonsoft.JsonDemo result = JsonConvert.DeserializeObject<Demo>("{\"player\":0, \"size\":3}");Example console app:
using System;
using Newtonsoft.Json;
namespace Demo
{
public class Demo
{
public int player { get; set; }
public int size { get; set; }
}
class Program
{
static void Main()
{
Demo result = JsonConvert.DeserializeObject<Demo>("{\"player\":0, \"size\":3}");
Console.WriteLine(result.player); // "0"
Console.WriteLine(result.size); // "3"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With