How to Get Some Values from a JSON String in C#

How to get some values from a JSON string in C#?

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Happy coding!

Get value from a Json string

The actual problem is that you are trying to parse this to JObject when you actually have an array of objects. You can first parse it to an array, then index the array to select the only object, and select your CompanyID key then grab the value as an int

var Result = "[{\"CompanyID\":32,\"Roles\":[\"Admin\"]}]";
// Parse your Result to an Array
var jArray = JArray.Parse(Result);
// Index the Array and select your CompanyID
var obj = jArray[0]["CompanyID"].Value<int>();

Alternatively, you can also map the JSON to a concrete type if it's a structure you will work with often. This is more beneficial as you will have compile time checking - in the event of making a spelling mistake or capitalization error when selecting one of the keys.

class Program
{
static void Main(string[] args)
{
var Result = "[{\"CompanyID\":32,\"Roles\":[\"Admin\"]}]";
var cList = JsonConvert.DeserializeObject<List<Company>>(Result);

var obj = cList.First().CompanyID;
}
}

public class Company
{
public int CompanyID { get; set; }
public List<string> Roles { get; set; }
}

How to get values from a JSON string in C#

For JSON manipulation, Json.NET may fit your needs.

It's support LINQ to JSON. You can retrieve the BTC info with below statements.

    var btcLastTradedPrice = JObject.Parse(json).SelectToken("BTC.last_traded_price");
Console.WriteLine(btcLastTradedPrice);

// Result: 3699003.04

The complete code for this sample:

using System;
using Newtonsoft.Json.Linq;

public class Program
{

public static void Main()
{
var json = @"{
""BTC"": {
""highest_buy_bid"": 3699003.04,
""lowest_sell_bid"": 3703660.94,
""last_traded_price"": 3699003.04,
""yes_price"": 3597618.7,
""volume"": {
""max"": ""3750000.00"",
""min"": ""3577155.82"",
""volume"": 43.12889007
}
},
""XRP"": {
""highest_buy_bid"": 95.2,
""lowest_sell_bid"": 95.3,
""last_traded_price"": 95.2,
""yes_price"": 95,
""volume"": {
""max"": ""97.91"",
""min"": ""93.20"",
""volume"": 329050.21
}
},
""NEO"": {
""highest_buy_bid"": 4241.3,
""lowest_sell_bid"": 4273.03,
""last_traded_price"": 4244.85,
""yes_price"": 4223.47,
""volume"": {
""max"": ""4296.35"",
""min"": ""4178.65"",
""volume"": 3988.2717
}
},
}";
var btcLastTradedPrice = JObject.Parse(json).SelectToken("BTC.last_traded_price");
Console.WriteLine(btcLastTradedPrice);
}
}

extracting a value from a JSON string

If you use Newtonsoft, as suggested in another answer, you don't even have to create a class.

JObject temp = JObject.Parse(rawJsonData);
var a1 = temp["a1"];

How to read value from JSON which is 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>();

c# get values from json

Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.

At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.

You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).

Something like this:

public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}

and

JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);

Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.

How to retrieve value from Json string in C#

Here's a small console application showing how you'd retrieve it using Json.NET. In your case the string, "json" would be retrieved from the response.

static void Main()
{
string json = @"
{ 'expires': 'Sat, 19 May 2046 04:10:58 + 0000', 'copy_ref': 'SMJNA2wxbGZbnmbnm', 'Result': null, 'error': null }";

JObject jObj = JObject.Parse(json); // Parse the object graph
string copyRef = jObj["copy_ref"].ToString(); // Retrive value by key

Console.WriteLine(copyRef);
}

How can I get the values of some part of a json string?

That json property contains a string of more JSON, so you have to deserialize that again, the same way you did the whole outer structure.

So now that you have your convert array, you can pull out the first object, grab the value of json and deserialize that:

var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(convert[0]["json"]);

Then you can pull each value out like this:

var id = json["Id"];

Mind you, the JSON in your question isn't actually valid. There are a few errors in it. But I'm assuming that they're just copy/paste errors and the web service is actually returning valid JSON.

How to extract specific value from this json string using linq

You have JSON Path, that can be used to select specific element(s) from the JSON string.
see Newtonsoft example, or you can use this JsonPath Nuget package.

The JsonPath Nuget can be used like below,

    var input = "$.downloads.csv.href";
var path = JsonPath.Parse(input);
var hrefVal = path.Evaluate(jsonStr);



Related Topics



Leave a reply



Submit