简体   繁体   中英

Deserialise Json file with newtonsoft and query with linq

I'm new to Newtonsoft and I'm trying to deserialise my json file then query specific data points from it. Here is a sample of the json.

[
    {
        "reward_type": "1",
        "rejected": "0",
        "user_id": "538653",
        "granted": "0"
    },
    {
        "reward_type": "5",
        "rejected": "0",
        "user_id": "536345",
        "granted": "1"
    },
    {
        "reward_type": "5",
        "rejected": "0",
        "user_id": "539493",
        "granted": "1"
    }
]

I'm trying to query the values after each type. I've been trying to wrap my head around the documentation for Json.net for a few days, but I'm having trouble finding examples for deserializing files.

Here is what I've been using to parse the file.

InitializeComponent();
        JArray adData1 = JArray.Parse(File.ReadAllText(@"c:\ads.json"));
        using (StreamReader file = File.OpenText(@"c:\ads.json"))
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            JsonSerializer serializer = new JsonSerializer();
            JArray adData2 = (JArray)serializer.Deserialize(file, typeof(JArray));

            JObject rewardType = (JObject)adData2[1];
            label1.Text = rewardType.ToString();
        }

Any help is appreciated.

From the suggestions:

Its only useable if the data have a common structure. You can Replace the DataTypes in the POCO, if you like

The POCO

public class Stuff {
    public string reward_type { get; set; }
    public string rejected { get; set; }
    public string user_id { get; set; }
    public string granted { get; set; }
}

How to use:

public void doThings() { 
// var s = File.ReadAllText("yourfilename.json");
    var s = @"{
""reward_type"": ""1"",
""rejected"": ""0"",
""user_id"": ""538653"",
""granted"": ""0""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""536345"",
""granted"": ""1""
},
{
""reward_type"": ""5"",
""rejected"": ""0"",
""user_id"": ""539493"",
""granted"": ""1""
}";
    // [] is needed to make it recognize it as list
    var listOfStuff = JsonConvert.DeserializeObject<List<Stuff>>("["+s+"]");
    foreach (var item in listOfStuff)
    {
        Console.WriteLine(item.user_id);
    }

}

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