artist
artist

Reputation: 329

How to read value from JSON which is string

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 ?

Upvotes: 4

Views: 13744

Answers (4)

Ben Krueger
Ben Krueger

Reputation: 1536

You could create a class:

public class MyObject
{
    public int Player {get; set;}
    public int Size {get; set;}
} 

And then deserialize the JSON string using something like JSON.NET:

MyClass myClassObject = JsonConvert.DeserializeObject<MyObject>(data);
var playerId = myClassObject.Player;

Upvotes: 2

Kyle B
Kyle B

Reputation: 2889

Add the Nuget package for JSON.net:

In the Nuget Package Manager search for "Newtonsoft.Json".

Or use the console:

Install-Package Newtonsoft.Json

Once installed you can use the following code for an anonymous type:

using Newtonsoft.Json;

var anonymousTypeDefinition = new { player = -1, size = -1 };
var player = JsonConvert.DeserializeAnonymousType(data, anonymousTypeDefinition);

Or you can use the following code for a strong type:

public class Player
{
    int Size { get; set; }
    int Player { get; set; }
}

// in the console
var player = Newtonsoft.Json.JsonConvert.DeserializeObject<Player>(data);

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109567

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

Upvotes: 2

Saeed Bolhasani
Saeed Bolhasani

Reputation: 580

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>();

Upvotes: 9

Related Questions