Domanda Risolto Aiuto Deserializzazione Json In C#

  • Autore discussione Utente cancellato 275412
  • Data d'inizio
U

Utente cancellato 275412

Ciao io ho il seguente JSON e sto usando newtonsoft.json:
JSON:
 "meta": {
      "hl": "en-US",
      "balance": 197182.32949635,
      "page": 1,
      "query": "covid 19",
      "results": 7,
      "result_stats": null,
      "duration": "d",
      "time_taken": 0.0021414756774902,
      "gl": "us"
    },
    "results": {
      "organic": [
        {
          "cache_url": null,
          "title": "example",
          "snippet": "17 hours ago ",
          "rank": 1,
          "url": "example.com",
          "snippet_html": "<span>29 mins ago</span>",
          "rich_snippet": null
        },
        {
          "cache_url": null,
          "title": "Example",
          "snippet": "29 mins ago",
          "rank": 2,
          "url": "example.com",
          "snippet_html": "<span>29 mins ago</span>",
          "rich_snippet": null
        }
      ],
      "people_also_ask": [
        {
          "question": "null",
          "source": "https://www.example.com"
        },
        {
          "question": "null",
          "source": "https://www.example.org"
        }
      ],
      "featured_snippet": null
    }
  },
  "tip": "For production and high volume use, please use https://example.com directly."
}
e io devo estrarre i contenuti di url e di title e mi sono visto qualche tutorial e devo fare così per deserializzarlo
qualcuno sa come posso realizzare la classe che dovrà contenere url e title?
@nullptr @JunkCoder @DispatchCode sapete aiutarmi please?
 
Ti faccio un esempio simile al tuo, penso sia ciò che intendi.

Ho semplificato un pò il JSON per questioni di tempo (così non puoi nemmeno fare proprio copia-incolla).
Codice:
        string json = @"
            {
            ""results"": {
             ""organic"": [
                {
                  ""cache_url"": null,
                  ""title"": ""example"",
                  ""snippet"": ""17 hours ago"",
                  ""rank"": 1,
                  ""url"": ""example.com"",
                  ""snippet_html"": ""<span>29 mins ago</span>"",
                  ""rich_snippet"": null
                },
                {
                  ""cache_url"": null,
                  ""title"": ""Example"",
                  ""snippet"": ""29 mins ago"",
                  ""rank"": 2,
                  ""url"":""example.com"",
                  ""snippet_html"": ""<span>29 mins ago</span>"",
                  ""rich_snippet"": null
                }
              ],
              ""people_also_ask"": [
                {
                  ""question"": ""null"",
                  ""source"": ""https://www.example.com""
                },
                {
                  ""question"": ""null"",
                  ""source"": ""https://www.example.org""
                }
              ]
            }
          }";

Le classi per rappresentare il tutto sono:

C#:
    class RootObject
    {
        [JsonProperty("results")]
        public Results Results { get; set; }
    }

che è di fatto il contenitore di tutto.

All'interno di Results ci sono due List<> (organic e people also ask):

C#:
    class Results
    {
        [JsonProperty("organic")]
        public List<Organic> Organics { get; set; }
        [JsonProperty("people_also_ask")]
        public List<PeopleAsk> PeopleAsk { get; set; }
    }

Quelle classi sono:
C#:
    class Organic
    {
        [JsonProperty("cache_url")]
        public string CacheUrl { get; set; }
        [JsonProperty("title")]
        public string Title { get; set; }
        [JsonProperty("snippet")]
        public string Snippet { get; set; }
        [JsonProperty("rank")]
        public int Rank { get; set; }
        [JsonProperty("url")]
        public string Url { get; set; }
        [JsonProperty("snippet_html")]
        public string SnippetHtml { get; set; }
        [JsonProperty("rich_snippet")]
        public string URichSnippet { get; set; }
    }
   
    class PeopleAsk
    {
       [JsonProperty("question")]
        public string Question { get; set; }
        [JsonProperty("source")]
        public string Source { get; set; }
    }

Codice completo:
C#:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
                   
public class Example
{
    public static void Main()
    {
        string json = @"
            {
            ""results"": {
             ""organic"": [
                {
                  ""cache_url"": null,
                  ""title"": ""example"",
                  ""snippet"": ""17 hours ago"",
                  ""rank"": 1,
                  ""url"": ""example.com"",
                  ""snippet_html"": ""<span>29 mins ago</span>"",
                  ""rich_snippet"": null
                },
                {
                  ""cache_url"": null,
                  ""title"": ""Example"",
                  ""snippet"": ""29 mins ago"",
                  ""rank"": 2,
                  ""url"":""example.com"",
                  ""snippet_html"": ""<span>29 mins ago</span>"",
                  ""rich_snippet"": null
                }
              ],
              ""people_also_ask"": [
                {
                  ""question"": ""null"",
                  ""source"": ""https://www.example.com""
                },
                {
                  ""question"": ""null"",
                  ""source"": ""https://www.example.org""
                }
              ]
            }
          }";
       
        RootObject obj1 = JsonConvert.DeserializeObject<RootObject>(json);
       
        foreach (Organic organic in obj1.Results.Organics)
        {
            Console.WriteLine("URL: " + organic.Url);
            Console.WriteLine("Title: " + organic.Title);
            Console.WriteLine();
        }
       
        RootObject obj2 = JsonConvert.DeserializeObject<RootObject>(json);
        List<PeopleAsk> PeopleAsk = obj2.Results.PeopleAsk;
       
        foreach (PeopleAsk people in PeopleAsk)
        {
            Console.WriteLine("URL: " + people.Question);
            Console.WriteLine("Title: " + people.Source);
            Console.WriteLine();
        }
    }

    class RootObject
    {
        [JsonProperty("results")]
        public Results Results { get; set; }
    }
   
    class Results
    {
        [JsonProperty("organic")]
        public List<Organic> Organics { get; set; }
        [JsonProperty("people_also_ask")]
        public List<PeopleAsk> PeopleAsk { get; set; }
    }
   
    class Organic
    {
        [JsonProperty("cache_url")]
        public string CacheUrl { get; set; }
        [JsonProperty("title")]
        public string Title { get; set; }
        [JsonProperty("snippet")]
        public string Snippet { get; set; }
        [JsonProperty("rank")]
        public int Rank { get; set; }
        [JsonProperty("url")]
        public string Url { get; set; }
        [JsonProperty("snippet_html")]
        public string SnippetHtml { get; set; }
        [JsonProperty("rich_snippet")]
        public string URichSnippet { get; set; }
    }
   
    class PeopleAsk
    {
       [JsonProperty("question")]
        public string Question { get; set; }
        [JsonProperty("source")]
        public string Source { get; set; }
    }
}

Se vuoi solo alcuni attributi puoi anche fare così:
C#:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
                   
public class Example
{
    public static void Main()
    {
        string json = @"
            {
            ""results"": {
             ""organic"": [
                {
                  ""cache_url"": null,
                  ""title"": ""example"",
                  ""snippet"": ""17 hours ago"",
                  ""rank"": 1,
                  ""url"": ""example.com"",
                  ""snippet_html"": ""<span>29 mins ago</span>"",
                  ""rich_snippet"": null
                },
                {
                  ""cache_url"": null,
                  ""title"": ""Example"",
                  ""snippet"": ""29 mins ago"",
                  ""rank"": 2,
                  ""url"":""example.com"",
                  ""snippet_html"": ""<span>29 mins ago</span>"",
                  ""rich_snippet"": null
                }
              ],
              ""people_also_ask"": [
                {
                  ""question"": ""null"",
                  ""source"": ""https://www.example.com""
                },
                {
                  ""question"": ""null"",
                  ""source"": ""https://www.example.org""
                }
              ]
            }
          }";
       
        RootObject obj1 = JsonConvert.DeserializeObject<RootObject>(json);
       
        foreach (Organic organic in obj1.Results.Organics)
        {
            Console.WriteLine("URL: " + organic.Url);
            Console.WriteLine("Title: " + organic.Title);
            Console.WriteLine();
        }
    }

    class RootObject
    {
        [JsonProperty("results")]
        public Results Results { get; set; }
    }
   
    class Results
    {
        [JsonProperty("organic")]
        public List<Organic> Organics { get; set; }
    }
   
    class Organic
    {
        [JsonProperty("title")]
        public string Title { get; set; }
        [JsonProperty("url")]
        public string Url { get; set; }
    }
}

Qui puoi provarlo anche online: https://dotnetfiddle.net/5I8rOx
 
Ultima modifica da un moderatore:
Grazie per le risposte io avevo fatto:

C#:
public class JsonUtile
{
    public string url="";
    public string title="";
}

Però non avevo capito che in JSON devo usare la gerarchia per prendere i valori.
Messaggio unito automaticamente:

Raga comunque ho:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using Newtonsoft.Json;

namespace MySearchEngine
{
    class Engine
    {
        class Organic
        {
            [JsonProperty("title")]
            public string Title { get; set; }
            [JsonProperty("url")]
            public string Url { get; set; }


        }
        class Results
        {
            [JsonProperty("organic")]
            public List<Organic> Organics { get; set; }
        }
        class JsonUseful
        {
            [JsonProperty("results")]
            public Results Result { get; set; }
        }
        public async Task<string> Search(string s)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("example.com"),
                Headers =
                {
                    { "x-rapidapi-key", "key" },
                    { "x-rapidapi-host", "example.com" },
                },
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                return (string)await response.Content.ReadAsStringAsync();

            }
        }
        public void PrintJson(string json)
        {
            string json1 = Convert.ToString(JsonConvert.DeserializeObject(json));
            JsonUseful x = JsonConvert.DeserializeObject<JsonUseful>(json1);
            foreach (Organic n in x.Result.Organics)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Ho controllato molte volte il programma e la variabile json1 contiene il .json corretto ma non capisco perché non riesco a deserializzare ed il problema credo sia qui:

C#:
JsonUseful x = JsonConvert.DeserializeObject<JsonUseful>(json1);
            foreach (Organic n in x.Result.Organics)
            {
                Console.WriteLine(n);
            }
Perché come exception mi dice che engine.jsonuseful.result non contiene organics
Messaggio unito automaticamente:

qui il messsagio di errore preciso:
MySearchEngine.Engine.JsonUseful.Result.get ha restituito null.
Messaggio unito automaticamente:

A mi ero sbagliato io che ho saltato un parametro nel json potete chiudere