簡體   English   中英

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

[英]how can i C# Deserialize JSON list WinForm Combobox?

在選擇組合框 1 中的項目后,我想打印出組合框 2 中選擇的數組的內容。

在此處輸入圖像描述

喜歡這張照片

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

}

JSON 文件看起來像這樣

class 定義如下:

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

但我不知道如何閱讀 object 中的內容。

我感謝提供的任何幫助。 提前致謝。

假設Movie屬性包含一個模式,其動作類型首先是字典/對象,

  1. 將 JSON 反序列化為Root
  2. 通過將值與所選操作類型匹配來從root.Movie獲取索引。
  3. 通過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}");
}

樣品 .NET 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM