Search code examples
javaservletsjavax.json

JSON Object is built incorrectly


I am trying to get data from my SQL. The Data from my Servlet is put into an array list. After that I build a JSON object and pass it to my JSP file. Now my browser is receiving the Objects really weird.

Also I can only call the first 3 of them. I tried to get all from the list with a for loop but that gave me an error. Any ideas what I am doing wrong? Oh and I am also not allowed to use JQuery. :(

I receive my JSON like this:

    {"id":"1GürtelA","kategorie":"2schuheS","oberkategorie":"3HoseB"}

But it should be:

    {"id":"1", "kategorie":"Gürtel", "oberkategorie":"A"}
    {"id":"2", "kategorie":"schuhe", "oberkategorie":"S"}
    {"id":"3", "kategorie":"Hose", "oberkategorie":"B"}

Here is the Part of my Servlet:

        List<KategorieBean> kategorien = displayKat();

        HttpSession session = request.getSession();
        session.setAttribute("kategorie", kategorien);

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        
        String resultJson = Json.createObjectBuilder()
                .add("id", (kategorien.get(0).toString()))
                .add("kategorie", (kategorien.get(1).toString()))
                .add("oberkategorie", (kategorien.get(2).toString()))     
                .build()
                .toString();
        
        PrintWriter writer = response.getWriter();
        writer.print(resultJson);
        writer.flush();

And here is toString I had to override.

    @Override
    public String toString() {
        return id + kategorie + oberK ;
       // This method is in my Bean
    }

Solution

  • It seems you're using javax.json API, and your expected output is not valid JSON.

    It should be an array:

    [{"id":"1", "kategorie":"Gürtel", "oberkategorie":"A"},
    {"id":"2", "kategorie":"schuhe", "oberkategorie":"S"},
    {"id":"3", "kategorie":"Hose", "oberkategorie":"B"}]
    

    To achieve this you need to fix your JSON building code (assuming that you have proper getters in the KategorieBean class):

    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    for (KategorieBean category : kategorien) {
        JsonObjectBuilder itemBuilder = Json.createObjectBuilder();
        arrayBuilder.add(
            itemBuilder
                .add("id", category.getId())
                .add("kategorie", category.getKategorie())
                .add("oberkategorie", category.getOberK())
                .build()
        );
    }
    String resultJson = arrayBuilder.build().toString();
    

    Also this code will return all items in the category list, not only the first three ones.