mapper.readValue не поддерживает JSON Views - PullRequest
0 голосов
/ 03 декабря 2018

Я использую JSONView, чтобы скрыть вещи от показа в API.Все работает, если я хочу иметь не читаемый JSON.Проблема в том, что я также пытаюсь prettify json, чтобы он выглядел более читабельным.Последняя в последней строке в приведенном ниже методе делает это:

@RequestMapping(path = "/questions")
public @ResponseBody List<Question> questionListRest() throws IOException { 
    ObjectMapper mapper = new ObjectMapper();
    String result = mapper
      .writerWithView(Views.Public.class)
      .writeValueAsString((List<Question>) questionRepository.findAll());
    List<Question> JsonList = mapper.readValue(result, new TypeReference<List<Question>>(){});
    return JsonList;
}    

Тем не менее, он инициализирует «ответ» как ноль, даже если ответ должен быть полностью скрыт от json (и скрыт отстрока json перед вызовом mapper.readValue):

[ { "questionId" : 6, "questionName" : "Which of the following would you most likely eat?", "questionType" : "checkbox", "values" : [ "A chainsaw", "A table", "An Apple" ], "answers" : null }, { "questionId" : 7, "questionName" : "What countries have you visited", "questionType" : "checkbox", "values" : [ "Finland", "Sweden", "Estonia" ], "answers" : null }, { "questionId" : 8, "questionName" : "Where did you last feel unconfortable", "questionType" : "checkbox", "values" : [ "At a bar", "While coding spring", "While eating an unsliced long sub" ], "answers" : null } ]

Вот мой класс вопросов:

@Entity
public class Question {

@JsonIgnore
private static AnswerRepository answerRepository; 

@JsonIgnore
private static CategoryRepository categoryRepository;   

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long questionId;
private String questionName;  
private String questionType; //text, radio, checkbox..
private String[] values;


public Question(String questionName, String questionType, Category category, String[] values) {
    super();
    this.questionName = questionName;
    this.questionType = questionType;
    this.category = category;
    this.setValues(values);
}

public Question(String questionName, String questionType, Category category) {
    super();
    this.questionName = questionName;
    this.questionType = questionType;
    this.category = category;
}   

@ManyToOne(cascade = {CascadeType.MERGE})
@JoinColumn(name = "categoryid")
@JsonBackReference
private Category category;  

@JsonView(Views.Internal.class)
public List<Answer> getAnswers() {
    return answers;
}

public void setAnswers(List<Answer> answers) {
    this.answers = answers;
}

@JsonView(Views.Internal.class)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "question")
@JsonManagedReference
private List<Answer> answers;   

public Question() {
    super();
}
... getters and setters ...

Вот json перед тем, как readValue вызываетсяна нем (например, когда result зарегистрировано) [{"questionId":6,"questionName":"Which of the following would you most likely eat?","questionType":"checkbox","values":[ "A chainsaw", "A table", "An Apple" ]},{"questionId":7,"questionName":"What countries have you visited","questionType":"checkbox","values":[ "Finland", "Sweden", "Estonia" ]},{"questionId":8,"questionName":"Where did you last feel unconfortable","questionType":"checkbox","values":[ "At a bar", "While coding spring", "While eating an unsliced long sub" ]}]

1 Ответ

0 голосов
/ 04 декабря 2018

Я «исправил» это, добавив @JsonInclude(JsonInclude.Include.NON_EMPTY) к полям в указанных пустых или пустых объектах.NON_EMPTY скрывает все значения, пустые или нулевые, NON_NULL только нулевые значения.Я, наверное, сначала спросил о том, что не так.

...