简体   繁体   English

使用newtonsoft反序列化Json文件并使用linq查询

[英]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. 我是Newtonsoft的新手,正在尝试反序列化json文件,然后从中查询特定的数据点。 Here is a sample of the json. 这是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. 几天来,我一直在努力寻找有关Json.net的文档的信息,但是我很难找到反序列化文件的示例。

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 您可以根据需要替换POCO中的数据类型。

The POCO 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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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