Home > OS >  How to get rid of the "\" while displaying a string object parsed with GSON in java
How to get rid of the "\" while displaying a string object parsed with GSON in java

Time:10-15

I am trying to get a clear array of JSON objects(books) using GSON. But whenever I run the following code:

public class Book {
    private int id;
    private String name;
    private String type;
    private boolean available;
    
    public Book(int id, String name, String type, boolean available) {
        super();
        this.id = id;
        this.name = name;
        this.type = type;
        this.available = available;
    }

    @Override
    public String toString() {
        return "{id="   id   ", name="   name   ", type="   type   ", available="   available   "},";
    }

    
}
import org.springframework.stereotype.Component;

import com.google.gson.Gson;

@Component
public class BookService {

    private int size = 0;
    public  int len = 6;
    public Book Allbooks[] = new Book[len];

    public Book AddBook(int id, String name, String type, boolean available) {
        if(id == len)
            return null;
        this.size  ;
        return Allbooks[this.size - 1] = createBook(id, name, type, available);


    }
    private Book createBook(int id, String name, String type, boolean available) {
        return new Book(id, name, type, available);
    }
    public Book[] bookRepo() {
        
        Allbooks[0] = AddBook(1, "One", "fiction", false);
        Allbooks[1] = AddBook(2, "Two", "non-fiction", true);
        Allbooks[2] = AddBook(3, "Three", "fiction", true);
        Allbooks[3] = AddBook(4, "Four", "fiction", false);
        Allbooks[4] = AddBook(5, "Five", "non-fiction", true);
        Allbooks[5] = AddBook(6, "Six", "non-fiction", true);

        return Allbooks;
    }
    public String[] showAll() {
        String[] arr = new String[Allbooks.length];
        for (int i = 0; i < arr.length; i  ) {
            arr[i] = new Gson().toJson(Allbooks[i], Book.class);
        }return arr;

    }
}
@RestController
class ControllerGET {

    @Autowired Status status;
    @Autowired BookService bookRepository;

    @GetMapping(path = {"/", ""})
    public String mainPage() {
        return "Welcome to Mile's simple book-API";
    }
    @GetMapping(path = "/status")
    public Status getStatus() {
        status.value = "OK";
        return status;
    }
    @GetMapping(path = "/books")
    public String[] getAllBooks() {
         bookRepository.bookRepo();
         return bookRepository.showAll();
    }
    //@GetMapping(path = "/books/:bookid")
    
}

I get the following output on my local host(Postman):

[
    "{\"id\":1,\"name\":\"One\",\"type\":\"fiction\",\"available\":false}",
    "{\"id\":2,\"name\":\"Two\",\"type\":\"non-fiction\",\"available\":true}",
    "{\"id\":3,\"name\":\"Three\",\"type\":\"fiction\",\"available\":true}",
    "{\"id\":4,\"name\":\"Four\",\"type\":\"fiction\",\"available\":false}",
    "{\"id\":5,\"name\":\"Five\",\"type\":\"non-fiction\",\"available\":true}",
    "null"
]

My goal is to make it look like this:

 {"id":1,
  "name":"One",
  "type":"fiction",
  "available":false}",
}

same for the other books. Please help me if you know a way. I'd be very thankful! ................................ ................................. ................................ ................................. ................................

CodePudding user response:

you don't need parse to json before return on springboot. Spring boot will do this for you ( using jackson lib for default )

try this:


  @GetMapping(path = "/books")
    public Book[] getAllBooks() { // return Book[] instead of String []
         bookRepository.bookRepo();
         return bookRepository.bookRepo(); // return all list of books
    }

CodePudding user response:

Delete the @Override toString() function. Directly return the gson().toJson() to the string.

However this is not good. You can define ArrayList instead of primitive array. So,

ArrayList<Book> AllBooks;
AllBooks.add(new Book(// add book 1));
AllBooks.add(new Book(// add book 2));
AllBooks.add(new Book(// add book 3));

and then on repo you can just return

return new Gson.toJson(AllBooks);

HOWEVER

This is not the best practice, as your books are stored on your server's RAM. So, reconsider to setup a database to assist the data relations. And in fact, spring provide jpa's @Entity to assist you for this kind of thing. When you declared your book as an entity, such as

@Entity
public class Book {
    private int id;
    private String name;
    private String type;
    private boolean available;
}

You can create a JpaRepository to retrieve all the data, e.g.

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}

And then just call the repository on your controller

@GetMapping(path = "/books")
public List<book> getAllBooks() {
    BookRepository bookRepo = new BookRepository();
    List<book> books = bookRepo.findAll();
    return books;
}
  • Related