Click here to Skip to main content
15,938,218 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
i have a text file (eg:empdetails.txt) which contain json data in it i need to read it . i have created table and class i just need to read the text file and print it as a list any one know how to read a text file please let me know

What I have tried:

//i have create a table of json content 
 String CREATE_EMPLOYEE_TABLE = "CREATE TABLE IF NOT  " + "EXISTS TABLE_EMPLOYEE(EMPLOYEE_ID INTEGER PRIMARY KEY,"
                   + " EMPLOYEE_SITEID  INTEGER, "
                   + " EMPLOYEE_GROUPID  INTEGER, "
                   + " EMPLOYEE_ID  INTEGER) ";
				     SqliteCommand TABLE_EMPLOYEE = new SqliteCommand(CREATE_EMPLOYEE_TABLE, db);

//and i created a class also
  public class EmployeeItem
    {

        public int Id { get; set; }
        public Int64 SiteID { get; set; }
        public Int64 GroupID { get; set; }
    }





using iTextSharp.text.pdf.parser;   // i can't install this package also

namespace DBCon
{
    public class EmployeeItem
    {

        public static void Main(string[] args)
        {

            try
            {
                string st = File.ReadAllText("file path of the text file") ;
                Console.WriteLine(st);
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");

                Console.WriteLine(e.Message);
            }
            Console.Read();

        }





//step by step explanation
//1
<Grid>
        <Button x:Name="abc" Content="NAVIGATE" HorizontalAlignment="Center" Height="100" Click="abc_Click"></Button>
    </Grid>


//2

private void abc_Click(object sender, RoutedEventArgs e)
       {
           this.Frame.Navigate(typeof(BlankPage1));
       }


// 3

public sealed partial class BlankPage1 : Page
  {
      public BlankPage1()
      {
          this.InitializeComponent();
          LoadSites();
      }
      void LoadSites()
      {
          List<String> BlankPage1 = DataAccess.Getemployee();
      }
  }


// 4 what mistake i have done in data base

public class DataAccess
  {
      public async static void InitializeDatabase()
      {
          await ApplicationData.Current.LocalFolder.CreateFileAsync("chillDatabase.db", CreationCollisionOption.OpenIfExists);
          string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "chillDatabase.db");
          using (SqliteConnection db =
              new SqliteConnection($"Filename={dbpath}"))
          {
              db.Open();

              // ========================{ TABLE_EMPLOYEE }===================================
              String CREATE_EMPLOYEE_TABLE = "CREATE TABLE IF NOT  " + "EXISTS TABLE_EMPLOYEE(EMPLOYEE_ID INTEGER PRIMARY KEY,"
      + " EMPLOYEE_SITEID  INTEGER, "
      + " EMPLOYEE_GROUPID  INTEGER, "
      + " EMPLOYEE_ID  INTEGER, )";
              SqliteCommand TABLE_EMPLOYEE = new SqliteCommand(CREATE_EMPLOYEE_TABLE, db);

              TABLE_EMPLOYEE.ExecuteReader();

          }
      }


      public static void AddEmployee(EmployeeItem Employee)
      {
          string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "chillDatabase.db");
          using (SqliteConnection db =
            new SqliteConnection($"Filename={dbpath}"))
          {
              db.Open();

              SqliteCommand insertCommand = new SqliteCommand();
              insertCommand.Connection = db;

              insertCommand.CommandText = "INSERT or REPLACE INTO SiteInfoTable VALUES (@EMP_SITEID, @EMP_GroupID, @EMP_ID,)";

              insertCommand.Parameters.AddWithValue("@EMP_SITEID ", Employee.SiteID);
              insertCommand.Parameters.AddWithValue("@EMP_GroupID ", Employee.GroupID);
              insertCommand.Parameters.AddWithValue("@EMP_ID ", Employee.Id);



              try
              {
                  insertCommand.ExecuteNonQuery();
              }
              catch (Exception ex)
              {
                  throw new Exception(ex.Message);
              }
          }

      }
      public static List<String> Getemployee()
      {




              try
              {
                   string rawJson = File.ReadAllText(@"E:\\database\\GetAllEmp.txt");

              List<EmployeeItem> employees = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);
          }
              catch (Exception e)
              {
                  Console.WriteLine("The file could not be read:");

                  Console.WriteLine(e.Message);
              }
              Console.Read();


          return null;

      }

  }


//5

ListView x:Name="itemList" Width="auto" Grid.Row="4" ItemsSource="{Binding Mode=TwoWay}" 
          Margin="60,0,60,0" BorderThickness="1" 
  BorderBrush="{ThemeResource SystemControlForegroundBaseMediumLowBrush}" Height="380" >
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:EmployeeItem">

                    <TextBlock Width="auto" Text="{Binding SiteID}"  FontSize="16"
                                   Foreground="Black"/>

                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>
Posted
Updated 17-Nov-22 19:09pm
v7
Comments
Graeme_Grant 17-Nov-22 9:09am    
Cannot see the raw JSON data in the file. Your problem could be that the property name casing does not match the property name casing in the class EmployeeItem.
Ailiseu Brigitta 17-Nov-22 9:14am    
can you correct my code
Graeme_Grant 17-Nov-22 9:19am    
Please update your question with the raw JSON so that we can see it to help you.

You have read the raw JSON file into a string, now you need to deserialize it.

1. You need a class structure to represent the JSON data. For that I like to use: JSON Utils: Generate C#, VB.Net, SQL TAble and Java from JSON[^]

2. Next you need to use a JSON serialization library. If .Net Framework 4.8 or earlier, use NuGet Gallery | Newtonsoft.Json[^], if Dot Net 3.1 or later, use https://learn.microsoft.com/en-us/dotnet/api/system.text.json[^]

Here are articles that I wrote for questions like this one:
* Working with Newtonsoft.Json in C# & VB[^]
* Working with System.Text.Json in C#[^]

UPDATE

Based on the raw JSON provided:
JavaScript
[
  {
    "Id": 5,
    "GID": 1,
    "SID": 34
  },
  {
    "Id": 4,
    "GID": 1,
    "SID": 33
  },
  {
    "Id": 3,
    "GID": 1,
    "SID": 32
  }
]

You need to change your EmployeeItem class as follows:
C#
public class EmployeeItem
{

	[JsonProperty("Id")]
	public int Id { get; set; }

	[JsonProperty("GID")]
	public long GroupID { get; set; }

	[JsonProperty("SID")]
	public long SiteID { get; set; }
}

The square brackets indicate an array of EmployeeItem objects, of which, with the reformatted JSON, we can see that there are 3 - IDs 5, 4, 3. We need to make sure that we deserialize a collection of objects.

The JsonProperty attribute maps the JSON property name to your EmployeeItem class property name. If the EmployeeItem class property name does not match or map, then no data will be deserialized.

Now you can Deserialize:
C#
string rawJson = File.ReadAllText("file path of the text file");

List<EmployeeItem> employees = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);

I cover all of this in the articles listed above including useful tools to help you with the raw data.

Hope this helps!
 
Share this answer
 
v5
Comments
Ailiseu Brigitta 17-Nov-22 23:48pm    
thank you very very much grant your code is working prety well but i can't print the data can you see my dataacess and find what erorr i have made
Graeme_Grant 18-Nov-22 0:05am    
Can you be more specific please... do you mean that the data is not displayed in the ListView? If I am reading your code correctly, you are binding to the Window itself but not binding to the collection of EmployeeItem. You need to bind to it specifically. The Collection should be of type ObservableCollection<employeeitem> and exposed as a property for the binding to work.
Ailiseu Brigitta 18-Nov-22 0:15am    
where should i need to right observable collection , sorry i am new to c#
Graeme_Grant 18-Nov-22 0:28am    
Ailiseu Brigitta 18-Nov-22 1:03am    
its ok grant i still now can't resolve my problem :-( its ok thank you for the time you spend for me :-)
1. Read the text
string st = File.ReadAllText("file path of the text file") ;

2. De-serialize the content to object (the sample uses Newtonsoft's library - one of the best)
EmployeeItem employeeItem = JsonConvert.DeserializeObject<EmployeeItem>(st);
 
Share this answer
 
Comments
Ailiseu Brigitta 17-Nov-22 6:54am    
can give more details for the code
Kornfeld Eliyahu Peter 17-Nov-22 6:56am    
I gave that only line you need... after that you have an object with the values from the file.
Ailiseu Brigitta 17-Nov-22 7:07am    
this error occurs//A field initializer cannot reference the non-static field, method, or property (st); this st can't be read
Kornfeld Eliyahu Peter 17-Nov-22 7:17am    
I would say that the content of the file does not in-line with the class you have...
Ailiseu Brigitta 17-Nov-22 7:10am    
please help me with this problem i have struck with this for 5 hours please :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900