Home > Back-end >  why jarray can not read json string
why jarray can not read json string

Time:11-06

i using jaray for reading json file

there is my c# code

Console.Write("enter database name:");
            string dbname = Console.ReadLine();
            string workingDirectory = Environment.CurrentDirectory;
            string dbdirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName;
            //string en_dbsdatas = File.ReadAllText(dbdirectory   @"\jsondb\dbsdatas.json");
            string en_dbsdatas = File.ReadAllText(dbdirectory   @"\jsondb\dbsdatas.json");
            JArray de_jArray = JArray.Parse(en_dbsdatas);
            bool flag = true;
            foreach (JObject i in de_jArray)
            {
                if ((string)i["dbname"] == dbname)
                {
                    Directory.Delete((string)i["dbpath"]);
                    flag = true;
                    break;
                }
                else
                {
                    flag = false;
                }
            }

and there is my json file (dbsdatas.json)

{
    "datas": [
      {
        "dbname": "mydb",
        "dbpath": "c:\\projects\\mydb"
        
      },
      {
        "dbname": "ssmydb",
        "dbpath": "c:\\prssojects\\mydb"
        
      }
    ]
  }

i catch an exeption in runnig program. my exeption is 'Error reading JArray from JsonReader. Current JsonReader item is not an array' in line JArray de_jArray = JArray.Parse(en_dbsdatas); whrere is the problem?

i catch an exeption in runnig program.

CodePudding user response:

your syntax is wrong, you can use

var de_jObject = JObject.Parse(en_dbsdatas);

or

JArray de_jArray = (JArray)JObject.Parse(en_dbsdatas)["datas"];

Your json is json object, not a json array. Data property inside of json is a json array

  • Related