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

时间:2017-12-08 14:47:27

标签: c# parsing json.net json-deserialization

我是Newtonsoft的新手,我试图反序列化我的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"
    }
]

我试图在每种类型之后查询值。我已经尝试过几天围绕Json.net的文档,但是我很难找到反序列化文件的示例。

以下是我用来解析文件的内容。

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

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

来自建议:

仅在数据具有共同结构时才可用。如果您愿意,可以替换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; }
}

使用方法:

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

}