将JSON数组反序列化为List

时间:2014-01-28 04:34:57

标签: c# json list deserialization

我正试图从一个超级巨大的JSON文件中获取推文...我想要的只是名为“text”的那些

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

1 个答案:

答案 0 :(得分:2)

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

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

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