我是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();
}
任何帮助都将不胜感激。
来自建议:
仅当数据具有共同的结构时才可用。如果您喜欢
,可以替换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);
}
}