How to generate a json with an object array

Asked

Viewed 35 times

-2

Hello, I’m trying to create a REST API, where in the GET method I should return a JSON in this style:

{questions:[{
  id: 1,
  question: 'pergunta 1',
  answers: [{
    answerText: 'resposta 1',
    correctAnswer: true
  },
  {
    answerText: 'resposta 2',
    correctAnswer: false
  }
 ]
}

I am using JPA and my code to generate a simple json uses only the class as follows:

package com.example.quizgame;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Question {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String question;
    private String answer;

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getQuestion() {
        return this.question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public String getAnswer() {
        return this.answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

}

would like to know how to convert a simple class to one that can insert an object array into the array.

1 answer

0


Inside your Question you can put a collection

@OneToMany
List<Answer> answers;

Research more on this note to avoid some problems that may happen, but basically that’s it.

  • Thank you very much, I was really wanting a light, I was very lost for being my first time using spring, I will go after yes, one more question if it is not uncomfortable it is possible to generate this JSON where the items are sorted randomly?

  • @Luisgustavorodriguesoliveir I think I don’t quite understand your question. In your example they are in order by id. You want random?

  • not that I always wanted to take the data randomly from the back end, but I already managed to solve thank you very much for everything

Browser other questions tagged

You are not signed in. Login or sign up in order to post.