我有一个带有以下格式化Json的文件
{
"Id": 0,
"MsgId": 125,
"ExceptionDetails": "whatever2"
}
{
"Id": 1,
"MsgId": 135,
"ExceptionDetails": "whatever2"
}
这完全是如何在没有布拉克的文件中
我需要解析这个文本文件并获取这些键的值,例如在这个例子中我需要得到0和1
var json = System.IO.File.ReadAllText(@"C:\development\commonArea\test3.txt");
var objects = JArray.Parse(json); // parse as array
foreach (JObject root in objects)
{
foreach (KeyValuePair<String, JToken> app in root)
{
if (app.Key == "Id")
{
var appName2 = app.Key;
Console.WriteLine(I HAVE NO IDEA);
}
}
}
由于
答案 0 :(得分:1)
var objects = JArray.Parse(json); // parse as array
foreach (JObject jobject in objects)
{
Console.WriteLine(jobject.Value<int>("Id"));
}
打印:
0
1
您提供了无效的JSON。我修改了它,以便它成为一个有效的JSON数组:
[
{ "Id": 0, "MsgId": 125, "ExceptionDetails": "whatever2" },
{ "Id": 1, "MsgId": 135, "ExceptionDetails": "whatever2" }
]
答案 1 :(得分:0)
创建一个匹配的类,然后使用反序列化器。这是使用System.Web.Script.Serialization
命名空间。
public class Item
{
public int Id { get; set; }
public int MsgId { get; set; }
public string ExceptionDetails { get; set; }
}
public class RootObject
{
public List<Item> Items { get; set; }
public RootObject DeserializeClass()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
RootObject obj = serializer.Deserialize<RootObject >(JSONSTRING);
return obj;
}
}