Answer the question
In order to leave comments, you need to log in
How to pull out from JSON (received via http) the value of one parameter in .Net?
I send a request to the server, the server sends an http response in JSON format, how can I parse one element of the request, for example guid, to assign it to the desired variable?
{
"channels" :
[
{
"guid" : "sHyGfRs",
"name" : "Name 1",
"rights" : "783",
"codec" : "h264",
"have_ptz" : "0",
}
]
Answer the question
In order to leave comments, you need to log in
As the comments have already said - use the Newtonsoft.Json library.
Then there are two ways
(for example, the test string looks like this -
1. Through the class. We create a class with a list of parameters and do
static void Main(string[] args)
{
string testJson = "{ \"channels\" : [ { \"guid\" : \"sHyGfRs\", \"name\" : \"Name 1\", \"rights\" : \"783\", \"codec\" : \"h264\", \"have_ptz\" : \"0\", } ] }";
var result = JsonConvert.DeserializeObject<RootObject>(testJson);
Console.WriteLine($"Name: {result.channels.FirstOrDefault().guid}");
}
public class Channel
{
public string guid { get; set; }
public string name { get; set; }
public string rights { get; set; }
public string codec { get; set; }
public string have_ptz { get; set; }
}
public class RootObject
{
public List<Channel> channels { get; set; }
}
static void Main(string[] args)
{
string testJson = "{'name':'Test','response':1}";
dynamic resultDynamic = JObject.Parse(testJson);
Console.WriteLine($"Name: {resultDynamic.name}, Response: {resultDynamic.response}");
}
Concise solution - JsonPath:
https://www.newtonsoft.com/json/help/html/QueryJso...
JObject o = JObject.Parse(@"
{
"channels" :
[
{
"guid" : "sHyGfRs",
"name" : "Name 1",
"rights" : "783",
"codec" : "h264",
"have_ptz" : "0"
}
]
}");
JToken guid = o.SelectToken("$.channels[0].guid");
Console.WriteLine(guid );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question