简体   繁体   English

我如何 C# 反序列化 JSON 列表 WinForm Combobox?

[英]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.在选择组合框 1 中的项目后,我想打印出组合框 2 中选择的数组的内容。

在此处输入图像描述

Like this picture喜欢这张照片

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

} }

The JSON file looks like this JSON 文件看起来像这样

The class is defined like this: class 定义如下:

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

But I don't know how to read what's in the object.但我不知道如何阅读 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,假设Movie属性包含一个模式,其动作类型首先是字典/对象,

  1. Deserialize JSON as Root .将 JSON 反序列化为Root
  2. Get the index from root.Movie by matching the value with the selected action type.通过将值与所选操作类型匹配来从root.Movie获取索引。
  3. Deserialize the next item by the index ( index + 1 ) in root.Movie as Dictionary<string, string> type.通过root.Movie中的索引 ( index + 1 ) 将下一项反序列化为Dictionary<string, string>类型。
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样品 .NET 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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