简体   繁体   中英

how can i C# Deserialize JSON list WinForm Combobox?

I would like to print out the contents of the array selected in Combo Box 2 after selecting an item in Combo Box 1.

在此处输入图像描述

Like this picture

{
"Movie": [
    "Action",
    {
        "Mad Max": "1979",
        "Terminator": "1984"
    },
    "SF",
    {
        "Star Wars": "1979"
    }
]

}

The JSON file looks like this

The class is defined like this:

public class Root
{
    public List<object> Movie { get; set; }
}

But I don't know how to read what's in the object.

I appreciate any help provided. Thanks in advance.

Assume that the Movie property contains a pattern with the action type first followed by a dictionary/object,

  1. Deserialize JSON as Root .
  2. Get the index from root.Movie by matching the value with the selected action type.
  3. Deserialize the next item by the index ( index + 1 ) in root.Movie as Dictionary<string, string> type.
using System.Collections.Generic;
using System.Text.Json;

Root root = JsonSerializer.Deserialize<Root>(json);
int index = root.Movie.FindIndex(x => x.ToString() == selected);
        
Dictionary<string, string> dict = JsonSerializer.Deserialize<Dictionary<string, string>>(root.Movie[index + 1].ToString());

// Print output
foreach (KeyValuePair<string, string> kvp in dict)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

Sample .NET Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM