JSON 文件的用户反序列化指定对象

Deserialize a specified object by a user of a JSON file

我有一个文本框,用户可以在其中输入一个数字,该数字将从特定电影中检索信息。我正在使用 Newtonsoft 的 Json.NET。

我有这个:

public class Movie
{
   public int number { get; set; }
   public string title { get; set; }
   public string director { get; set; }
}

public class RootObject
{
   public List<Movie> movies { get; set; }
}

private void button3_Click(object sender, EventArgs e)
{
    Movie movie = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\MoviesJSON.json"));

    enteredNumber = Int32.Parse(textBox1.Text);

    label7.Text = movie.title[enteredNumber]; <---- //I am not sure about this. But it's kind of what want to get to.
}

我想显示输入的电影名称(片名)

这是我的 JSON 文件:

{ 
    "movies": [
        {
            "number": 1,
            "title": "Unbroken",
            "director": "Angelina Jolie"
        },
        {
            "number": 2,
            "title": "Avatar",
            "director": "James Cameron"
        },
        {
            "number": 3,
            "title": "Batman: The Dark Knight",
            "director": "Christopher Nolan"
        }
    ]
}

更改此行:

label7.Text = movie[enteredNumber].title;

您需要提供您的电影 class 以使其清楚,如果有异常详细信息。

你的电影 class 好像是这样的:

public class Movie
{
   public List<String> title;
   public List<String> director;
   public List<DateTime> year;
   ...
}

如果是这样,它应该可以工作。 (我不得不说,这是一个糟糕的设计)

给定您的 类,以下辅助方法将在 JSON 电影数组中的 zero-based 索引处获取电影标题,给定用户键入的索引字符串:

    public static string GetMovieTitle(string json, string enteredNumberText)
    {
        var root = JsonConvert.DeserializeObject<RootObject>(json);
        try
        {
            var enteredNumber = Int32.Parse(enteredNumberText);
            if (enteredNumber < 0 || enteredNumber >= root.movies.Count)
                return null;
            return root.movies[enteredNumber].title;
        }
        catch (System.FormatException)
        {
            // Invalid number typed by the user.  Handle if desired.
            throw;
        }
        catch (System.OverflowException)
        {
            // Too large or small number typed by the user.  Handle if desired.
            throw;
        }
    }