简体   繁体   中英

Deserializing a JSON Array as List

I'm trying to grab the tweets from a super huge JSON file... all i want are the ones named "text"

JSON file looks like this:

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

EDIT: It's only grabbing the last text.. "text2".. why is it not grabbing everything as a list?

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

Your JSON is an array with just one object, which has multiple properties with the same name! And that's why you're only getting value from the last property.

It needs to be like that to be actually an array of objects, and each to have just one text property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM