Home > Enterprise >  Get multiples Arrays from dictionary Object
Get multiples Arrays from dictionary Object

Time:10-03

I have a JSON call, this brings me an object with four Arrays.

HttpWebRequest apiRequest = WebRequest.Create(url) as HttpWebRequest;

    string apiResponse = "";
    using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
    {
        StreamReader reader = new StreamReader(response.GetResponseStream());
        apiResponse = reader.ReadToEnd();
    }

    var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(apiResponse);
    var results = dict["results"];

Then i use var dict to storage this four arrays, later i have var results to select an specific array. In this case, the array i want is "results".

var results "output":
var results "output"

The problem is i want access the data for each array, but i don't know how do this.

    ArrayList list = (ArrayList)results;
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < list.Count; i  )
    {

        if (builder.Length > 0)
        {
            builder.Append(", ");
        }
        object current = list[i];
        builder.Append(current);
    }
    LblTitle.Text = builder.ToString();

I see this code in other post and i adapt to my code, but this only brings me this System.Collections.Generic.Dictionary'2[System.String,System.Object], for each array.

I want something like this string[] arrayresult = builder.ToString(); string[] arrayresult2 = builder.ToString(); etc, for each array in the object results. And later access each array data like this LblTitle.Text = arrayresult[1]; LblTitle2.Text = arrayresult2[1];

Edit: Adding JSON Example

"{\"page\":1,\"results\":[{\"adult\":false,\"backdrop_path\":\"/7ABsaBkO1jA2psC8Hy4IDhkID4h.jpg\",\"genre_ids\":[28,12,14,878],\"id\":19995,\"original_language\":\"en\",\"original_title\":\"Avatar\",\"overview\":\"In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, but becomes torn between following orders and protecting an alien civilization.\",\"popularity\":1363.938,\"poster_path\":\"/jRXYjXNq0Cs2TcJjLkki24MLp7u.jpg\",\"release_date\":\"2009-12-10\",\"title\":\"Avatar\",\"video\":false,\"vote_average\":7.5,\"vote_count\":26216},{\"adult\":false,\"backdrop_path\":\"/198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg\",\"genre_ids\":[878,28,12],\"id\":76600,\"original_language\":\"en\",\"original_title\":\"Avatar: The Way of Water\",\"overview\":\"Set more than a decade after the events of the first film, learn the story of the Sully family (Jake, Neytiri, and their kids), the trouble that follows them, the lengths they go to keep each other safe, the battles they fight to stay alive, and the tragedies they endure.\",\"popularity\":1000.602,\"poster_path\":\"/1yppMeTNQwDrzaUH4dRCx4mr8We.jpg\",\"release_date\":\"2022-12-14\",\"title\":\"Avatar: The Way of Water\",\"video\":false,\"vote_average\":0,\"vote_count\":0},{\"adult\":false,\"backdrop_path\":null,\"genre_ids\":[99],\"id\":287003,\"original_language\":\"en\",\"original_title\":\"Avatar: Scene Deconstruction\",\"overview\":\"The deconstruction of the Avatar scenes and sets\",\"popularity\":261.979,\"poster_path\":\"/uCreCQFReeF0RiIXkQypRYHwikx.jpg\",\"release_date\":\"2009-12-18\",\"title\":\"Avatar: Scene Deconstruction\",\"video\":false,\"vote_average\":9,\"vote_count\":3},{\"adult\":false,\"backdrop_path\":null,\"genre_ids\":[99],\"id\":111332,\"original_language\":\"en\",\"original_title\":\"Avatar: Creating the World of Pandora\",\"overview\":\"The Making-of James Cameron's Avatar. It shows interesting parts of the work on the set.\",\"popularity\":259.613,\"poster_path\":\"/d9oqcfeCyc3zmMal6eJbfj3gatc.jpg\",\"release_date\":\"2010-02-07\",\"title\":\"Avatar: Creating the World of Pandora\",\"video\":false,\"vote_average\":7,\"vote_count\":20}],\"total_pages\":3,\"total_results\":55}"

I convert this JSON to Class, thanks for the tip. This is my class now:

public class Result
{
    public bool adult { get; set; }
    public string backdrop_path { get; set; }
    public List<int> genre_ids { get; set; }
    public int id { get; set; }
    public string original_language { get; set; }
    public string original_title { get; set; }
    public string overview { get; set; }
    public double popularity { get; set; }
    public string poster_path { get; set; }
    public string release_date { get; set; }
    public string title { get; set; }
    public bool video { get; set; }
    public double vote_average { get; set; }
    public int vote_count { get; set; }
}

public class Root
{
    public int page { get; set; }
    public List<Result> results { get; set; }
    public int total_pages { get; set; }
    public int total_results { get; set; }
}

CodePudding user response:

I would suggest you create a proper C# class to deserialize your JSON into. We can't see how you JSON looks, so I'll just give a simple example. Let's say this is your JSON:

{
  "results": [
    [
      "foo",
      "bar"
    ],
    [
      "baz",
      "qux"
    ]
  ],
  "someOtherField": "someValue"
}

If you go to https://json2csharp.com/ you can convert this into a C# class like this:

public class Root
{
    public List<List<string>> results { get; set; }
    public string someOtherField { get; set; }
}

To deserialize and access the data, you simply do the following (I'm using System.Text.Json instead of JavaScriptSerializer - see comment below):

var root = JsonSerializer.Deserialize<Root>(apiResponse);
// ...
List<string> listResult = root.results[0];
List<string> listResult2 = root.results[1];
// ...
LblTitle.Text = listResult[1]; // "bar"
LblTitle2.Text = listResult2[1]; // "qux"

Please refer to the definition of JavaScriptSerializer:

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.

See here for how to use System.Text.Json .


If you want to use Newtonsoft.Json instead, you should replace JsonSerializer.Deserialize with JsonConvert.DeserializeObject:

var root = JsonConvert.DeserializeObject<Root>(apiResponse);
  • Related