【问题标题】:Deserialize a specified object by a user of a JSON file由 JSON 文件的用户反序列化指定对象
【发布时间】:2015-08-25 18:15:34
【问题描述】:

我有一个文本框,用户可以在其中输入一个数字,该数字将从特定电影中检索信息。我正在使用 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"
        }
    ]
}

【问题讨论】:

  • JSON 和 c# 类是什么样的?可能您应该反序列化 List&lt;Movie&gt;,但从您提供的代码中可以看出。
  • @dbc:我已经更新了!
  • 我们还需要看一个 JSON 的例子。还有,你说的//这一切都错了是什么意思?
  • @dbc:我已经添加了 JSON 文本并更改了评论。

标签: c# .net json windows visual-studio


【解决方案1】:

给定您的类,在给定用户键入的索引字符串的情况下,以下辅助方法将在 JSON 电影数组中从零开始的索引处获取电影标题:

    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;
        }
    }

【讨论】:

    【解决方案2】:

    改变这一行:

    label7.Text = movie[enteredNumber].title;
    

    【讨论】:

      【解决方案3】:

      您需要提供您的 Movie 类以使其清楚,并提供异常详细信息(如果有)。

      您的 Movie 课程似乎是这样的:

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

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

      【讨论】:

        猜你喜欢
        • 2021-12-17
        • 1970-01-01
        • 2023-02-22
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 2016-11-20
        • 1970-01-01
        相关资源
        最近更新 更多