Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read value from JSON which is string

Tags:

json

c#

parsing

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 ?

like image 903
artist Avatar asked Oct 24 '25 22:10

artist


2 Answers

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>();
like image 92
Saeed Bolhasani Avatar answered Oct 27 '25 12:10

Saeed Bolhasani


  1. Create a class for that JSON.

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).

  1. Add to your project a NuGet reference to Newtonsoft.Json
  2. Deserialize via Demo 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"
        }
    }
}
like image 37
Matthew Watson Avatar answered Oct 27 '25 11:10

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!