Harry
Harry

Reputation: 55

How to parse two different JSON formats

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"
  }
]

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);
        }
    }
}

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?

Upvotes: 0

Views: 1226

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129707

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();
}

Fiddle: https://dotnetfiddle.net/lA87Xo

Upvotes: 1

Related Questions