M
M
Maxim2018-02-05 15:15:37
JSON
Maxim, 2018-02-05 15:15:37

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

2 answer(s)
I
Ivan Arxont, 2018-02-06
@maxaprelsky

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

2. There is another way using dynamic (but you have arrays there, so I strongly do not recommend it)
static void Main(string[] args)
        {
            string testJson = "{'name':'Test','response':1}";

            dynamic resultDynamic = JObject.Parse(testJson);

            Console.WriteLine($"Name: {resultDynamic.name}, Response: {resultDynamic.response}");
        }

R
rodion-m, 2018-08-03
@rodion-m

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

It is convenient to use the service as a tester: jsonpath.com

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question