Muhammad
Muhammad

Reputation: 11

C# Picking a specific value from a response from server?

How to pick only a specific value from a server response ? Server is sending response in JSON format and I need only one specific value from the the entire response.

My code :

var exitEvent = new ManualResetEvent(false);
            var url = new Uri("wss://ws-feed.exchange.coinbase.com");
            using (var client = new WebsocketClient(url))
            {
                client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                client.ReconnectionHappened.Subscribe(info =>
                    Console.WriteLine($"Reconnection happened, type: {info.Type}"));
                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                client.Start();
                Task.Run(() => client.Send("{\"type\": \"subscribe\",\"product_ids\": [\"ETH-USD\"]," +
                    "\"channels\": [ \"level1\",\"heartbeat\",{\"name\": \"ticker\",\"product_ids\": [\"ETH-USD\"]}]}"));
                exitEvent.WaitOne();
            }

Here is the JSON Response:

Message received: {"type":"ticker","sequence":23072222086,"product_id":"ETH-USD","price":"4555.43","open_24h":"4582.28","volume_24h":"145928.12243540","low_24h":"4435","high_24h":"4637.39","volume_30d":"4882834.91966503","best_bid":"4555.43","best_ask":"4555.44","side":"sell","time":"2021-12-03T09:26:50.426810Z","trade_id":187917443,"last_size":"0.02365389"}

How can one pick only one specific value from entire response , Let say I want to pick the "Price" Value only.

Upvotes: 1

Views: 374

Answers (1)

miechooy
miechooy

Reputation: 3422

If it is just to read one property the fastests way is to use Newtonsoft.Json. So download above package and just use:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

var parsedJObject = JObject.Parse(response);
var price = parsedJObject["price"];

Edit:

client.MessageReceived.Subscribe(MessageReceived);

void MessageReceived(string message)
{
   var parsedJObject = JObject.Parse(response);
   var price = parsedJObject["price"];
}

Upvotes: 1

Related Questions