【问题标题】:Deserializing a JSON Array as List将 JSON 数组反序列化为列表
【发布时间】:2014-01-28 04:34:57
【问题描述】:

我正在尝试从一个超大的 JSON 文件中获取推文……我想要的只是那些名为“文本”的推文

JSON 文件如下所示:

[{"text":"A nice cup of #coffee can speed your day up, and so can Firefox.", "text":"test1",
"text":"test2"}]

编辑:它只抓取最后一个文本..“text2”..为什么不抓取所有内容作为列表?

public class JSONClasses
    {
        public class SingleTweet
        {
            [JsonProperty("text")]
            public string text { get; set; }
        }
    }

    public class JSONFunctions
    {
        //public static JSONRoot jsonFile = new JSONRoot();
        public static List<JSONClasses.SingleTweet> TweetList = new List<JSONClasses.SingleTweet>();

        public static bool Deserialize(string path)
        {            
            try
            {
                var filePath = File.OpenText(path);
                TweetList = JsonConvert.DeserializeObject<List<JSONClasses.SingleTweet>>(filePath.ReadToEnd());
                filePath.Close();
                return true;
            }
            catch (Exception)
            {
                Console.WriteLine("Could not Deserialize: " + path);
                return false;
            }
        }
    }

//test to see if it works:
JSONFunctions.Deserialize(AppOptions.JSONTwitterFilePath);

foreach (JSONClasses.SingleTweet temp in JSONFunctions.TweetList)
                Console.WriteLine(temp);

【问题讨论】:

  • 请重新打开..我修好了...
  • 你并没有真正解决任何问题。如果有的话,您的更新使您的问题无效。反序列化您最初发布的 JSON 工作正常...如果您希望我们能够帮助您,您需要发布您收到的 full 异常消息。
  • ....你得到的结果是什么?
  • 我不确定你们想从我这里得到什么?它捕获了一个异常,因为“Newtonsoft.Json.dll 中发生了'Newtonsoft.Json.JsonSerializationException' 类型的第一次机会异常”
  • 编辑:好吧,它不再出错了,但它只是抓住了最后一个“文本”.. test2.. 由于某种原因,列表中似乎没有其他任何内容.. 任何人都知道为什么?

标签: c# json list deserialization


【解决方案1】:

你的 JSON 是一个只有一个对象的数组,它有多个同名的属性!这就是为什么您只能从最后一个属性中获得价值。

它实际上是一个对象数组,每个对象只有一个 text 属性:

[
    {"text":"A nice cup of #coffee can speed your day up, and so can Firefox." },
    {"text":"test1" },
    {"text":"test2"}
]

【讨论】:

  • 废话,我知道这很简单。会尝试回来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多