我需要解析2种不同类型的JSON,如下所示:
JSON 1:
{
"projects": [
{
"sno": "1",
"project_name": "Abs",
"project_Status": "Live"
},
{
"sno": "2",
"project_name": "Cgi",
"project_Status": "Live"
}
]
}
JSON 2:
[
{
"sno": "1",
"project_name": "Disc",
"project_Status": "Live"
},
{
"sno": "2",
"project_name": "Rol",
"project_Status": "Live"
}
]
我正在按如下方式解析JSON 2:
using (StreamReader streamReader = new StreamReader(Path.Combine(Path.GetTempPath(), "sample.json")))
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
JObject jsonPayload = JObject.Load(reader);
jsonProfile = jsonPayload.ToString();
JObject json = JObject.Parse(jsonProfile);
}
}
}
我是否可以修改它以检查JSON是1型还是2型,然后解析它以将每个项目分配给不同的JObject?
答案 0 :(得分:1)
除非您的JSON很大(数千行),否则我将完全放弃读者。相反,请使用File.ReadAllText
将整个JSON文件读取为字符串,然后使用JToken.Parse
对其进行解析。从那里很容易检查您是否有一个数组(JSON 2)或包含一个数组的对象(JSON 1),然后进行相应处理:
string fileName = Path.Combine(Path.GetTempPath(), "sample.json");
string json = File.ReadAllText(fileName);
JToken token = JToken.Parse(json);
JArray array = (token.Type == JTokenType.Array) ? (JArray)token : (JArray)token["projects"];
foreach (JObject project in array)
{
Console.WriteLine("number: " + (string)project["sno"]);
Console.WriteLine("name: " + (string)project["project_name"]);
Console.WriteLine("status: " + (string)project["project_Status"]);
Console.WriteLine();
}