如何解析两种不同的JSON格式 [英] How to parse two different JSON formats
问题描述
我需要解析2种不同类型的JSON,如下所示:
I need to parse 2 different types of JSONs as shown below:
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:
I was parsing the JSON 2 as follows:
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?
Is it possible for me to modify this to check if the JSON is in type 1 or type 2 and then parse it to assign each project to a different JObject?
推荐答案
除非您的JSON很大(数千行),否则我将完全放弃读者.相反,请使用 JToken.Parse
.从那里很容易检查您是否有一个数组(JSON 2)或包含一个数组的对象(JSON 1),然后进行相应的处理:
Unless your JSON is large (thousands of lines), I would dispense with the reader altogether. Instead, read the whole JSON file into a string using File.ReadAllText
and parse it using JToken.Parse
. From there it is easy to check whether you have an array (JSON 2) or an object containing an array (JSON 1) and then process accordingly:
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();
}
提琴: https://dotnetfiddle.net/lA87Xo
这篇关于如何解析两种不同的JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!