解析C#中的json对象?

问题描述:

我使用System.Net.Json.JsonTextParser而在C#开发程序来解析JSON文件,所以我设置了col对象像下面根据教程:解析C#中的json对象?

JsonTextParser parser = new JsonTextParser(); 
JsonObject obj = parser.Parse(System.IO.File.ReadAllText(file)); 
JsonObjectCollection col = (JsonObjectCollection)obj; 

在这种情况下,我知道我能得到的值键(例如,"formats")像以下:

string Data = Convert.ToString(col["formats"].GetValue()); 

但是,我怎么能读一键下另一个JSON对象?对不起,我不知道怎么表达这一点,但是,例如,我有:

"formats" : {"key1" : "value11", "key2" : "value12"}, {"key1" : "value21", "key2" : "value22"} 

,我应该怎样做才能"formats"下的每个JSON对象?如何读取"key1"的每个值?

+2

只是出于好奇,你为什么不使用Json.NET? – Rafael

+2

只是一个建议,Newtonsoft JSON.NET https://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm可能是一个更好的库处理JSON,我认为你更有可能得到使用它的帮助。 – Novaterata

+0

是真正的json youre试图解析为jsonlint给我错误:解析错误第1行: “格式”:{\t“key1”:“value1 ---------^ 期待'EOF ','}',',',']','''''' –

你应该使用https://www.nuget.org/packages/Newtonsoft.Json/

你应该创建一个C#类coressponding您的JSON文件。

您的JSON文件将是:

public class Formats 
{ 
    public string Key1 {get; set;} 
    public string Key2 {get; set;} 
} 

,然后你的JSON文件转换为C#对象:

using (var streamReader = new StreamReader("file.json")) 
{ 
    string json = streamReader.ReadToEnd(); 
    var jsonObject = JsonConvert.DeserializeObject<List<Formats>>(json); 
    foreach(var obj in jsonObject) 
    { 
     Console.WriteLine($"Key1: {obj.Key1}, Key2: {obj.Key2}"); 
    } 
} 
+0

所以,如果我有更多的子项下的键,我可以像'obj .key1.key2.key3 ....'' – GreenRoof

+0

你可以用c#对象做任何事情,并且支持嵌套对象。 – Mightee