1

Im trying to create a "Library Database" as part of a university project in ASP.Net & C#, With Json used as a storage method.

Im a complete newbie to asp.net and c#, Yesterday someone was helping me figure out how to fill a range of text boxes in a form with the relevant data from a Json array, when each element in that array is selected using a Drop Down List. We managed to get that part of the code up and running but ive hit a new roadblock.

I need to know how to delete a data entry in a JSON Array.

Below is the code with the variables for my Json array

public class Book
{
    public string id { get; set; }
    public string title { get; set; }
    public string author { get; set; }
    public string year { get; set; }
    public string publisher { get; set; }
    public string isbn { get; set; }

    public Book(string id, string title, string author, string year, string publisher, string isbn)
    {
        this.id = id;
        this.title = title;
        this.author = author;
        this.year = year;
        this.publisher = publisher;
        this.isbn = isbn;       
    }
}

Below is the code for my Array

public class BookList
{
    public List<Book> bookList { get; set; }

    public BookList()
    {
        bookList = new List<Book>();
    }

    public object Where(Func<object, bool> p)
    {
        throw new NotImplementedException();
    }
}

Below is the CURRENT Json Data

{
  "bookList": [
    {
      "id": "1",
      "title": "Harry Potter and the Philosopher's Stone",
      "author": "J.K. Rowling",
      "year": "1997",
      "publisher": "Bloomsbury",
      "isbn": "0-7475-3269-9"
    },
    {
      "id": "2",
      "title": "The Hobbit",
      "author": "J. R. R. Tolkien",
      "year": "1937",
      "publisher": "George Allen & Unwin",
      "isbn": "054792822X"
    },
    {
      "id": "3",
      "title": "Nisekoi: False Love",
      "author": "Naoshi Komi",
      "year": "2014",
      "publisher": "Viz",
      "isbn": "9781421557991"
    }
  ]
}

Below is the current Code for my delete book page

public partial class DeleteBook : System.Web.UI.Page
{
    public const string FILENAME = @"C:\Users\User\Documents\Assessments\19383038_CSE2ICX_Assignment3\JsonFiles\BookList.Json";
    string jsonText = File.ReadAllText(FILENAME);
    BookList bookList = new BookList();

    public void Page_Load(object sender, EventArgs e)
    {
        bookList = JsonConvert.DeserializeObject<BookList>(jsonText);
        if (!IsPostBack)
        {
            ddl.DataTextField = "id";
            ddl.DataValueField = "id";
            ddl.DataSource = bookList.bookList;
            ddl.DataBind();
        }

        var book = bookList.bookList.Where(x => x.id == ddl.SelectedValue).FirstOrDefault();
        txtDeleteID.Text = book.id;
        txtDeleteTitle.Text = book.title;
        txtDeleteAuthor.Text = book.author;
        txtDeleteYear.Text = book.year;
        txtDeletePublisher.Text = book.publisher;
        txtDeleteIsbn.Text = book.isbn;
    }

    protected void btnDeleteBook_Click(object sender, EventArgs e)
    {
        // ...
    }

    protected void btnClearField_Click(object sender, EventArgs e)
    {
        // ...
    }
}

So in the Page load, the code is telling each of the text boxes in my form to read what data each variable contains within the array with regards to what ID i have selected in the drop down list.

Now what i need to do is DELETE that data and only that data. I dont want to refer to the data by name specifically, as this data base will allow people to enter other data and i need a method that figures out what the data is called, then deletes it. This applies to all of the data within each book. For example, Harry potter is a book listed in this library and I want to delete all information pertaining to Harry Potter when i click on the delete book button.

Unfortunately I am not experienced enough with accessing the information in JSON properly, Ive tried converting the array into a jobject but haven't had any luck on that path. and the .REMOVE function only lets me handle Int's , could someone please help me with solving this problem, or understanding how to manipulate this data.

Sorry for the long post, and if what i want inst clear enough let me know and ill do my best to explain in more detail. Thank you in advance for any help received.

4
  • 1
    I would suggest that, after you deserialize the json you can remove it from the list then re-serialize the list to json Commented Mar 16, 2018 at 12:04
  • Is it one og them project requirements that you use JSON as storage? If not, you really should use a real DB Commented Mar 16, 2018 at 12:14
  • Ive already deserialized the json file in the page load? my problem is im not sure how to remove data from it even after that. Commented Mar 16, 2018 at 12:14
  • @KrzysztofSkowronek Yes unfortunately all data has to be stored in a JSON file, the idea isnt using a database but learning how to make one from scratch, even if ill probably never do that strictly in c#. Commented Mar 16, 2018 at 12:15

1 Answer 1

2

In your button click remove

protected void btnDeleteBook_Click(object sender, EventArgs e)
{
   var itemToRemove = bookList.bookList.FirstOrDefault(r => r.id == ddl.SelectedValue);
   if(itemToRemove != null)
      bookList.bookList.Remove(itemToRemove);
}

this will delete the selected book from the bookList. Now serialize the list back to json.

string newJsonText = JsonConvert.SerializeObject(bookList);

Also rename your bookList class to something else because bookList.bookList looks very confusing. Maybe bookStore or so

Sign up to request clarification or add additional context in comments.

11 Comments

haha thanks good tip about the booklist, just doing it the way i learnt but ill start coming up with better names. EDIT: I needed to set it to bookList.booklist for it to r to recognise id. now when i ran the code there was an error when it reached remove. Ive been having issues with the remove function all night but everywhere says to use it. Am i doing something wrong elsewhere in the code?
Eddited with bookList.bookList As i said its confusing hehe try the new version.
Allright, so. Hooray it deleted the third book entry. BUT there is another issue
EDIT: Ive just realised it deleted booklist and the opening/closing {} brackets as well. any idea how to stop it from doing this?
You mean you rewrote the JSON? Maybe you made some mistake with the quotes?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.