gpt4 book ai didi

java - 返回带有键值对的 JSON

转载 作者:行者123 更新时间:2023-12-02 01:34:15 24 4
gpt4 key购买 nike

我使用此代码从 REST 端点生成响应:

if (result.hasErrors()) {
List<String> errorsList = new ArrayList<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
System.out.println("Validation error in field: " + error.getObjectName()
+ "! Validation error message: " + error.getDefaultMessage()
+ "! Rejected value:" + error.getRejectedValue());
errorsList.add(error.getField() + ": " + error.getDefaultMessage());
}

return ResponseEntity.ok(new StringResponseDTO(errorsList));
}

对象:

@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
@JsonTypeName("response")
public class StringResponseDTO {

private String redirect;

private List<String> errors;

public StringResponseDTO(String redirect) {
super();
this.redirect = redirect;
}

public StringResponseDTO(List<String> errors) {
this.errors = errors;
}

......
}

现在我得到这样的回复:

{
"response" : {
"errors" : [ "expiration_year: must not be null", "default_transaction_type: must not be null"]
}
}

我需要像这样更改它:

{
"response" : {
"errors" : [ "expiration_year": "must not be null", "default_transaction_type": "must not be null"]
}
}

有没有办法在不添加大量“”符号的情况下存档他的内容?

最佳答案

您在“想要的”结果中表达的格式无效。
例如,您可以使用 Jackson(或 GSON,具体取决于您使用的库)类

(注意, objectMapperObjectMapper 的实例)

public class StringResponseDTO {
private String redirect;
private TreeNode errors;

public StringResponseDTO(final String redirect) {
this.redirect = redirect;
}

public StringResponseDTO(final Collection<? extends FieldError> errors) {
this.errors =
errors.stream()
.collect(Collector.of(
objectMapper::createObjectNode,
(json, e) -> json.put(e.getField(), e.getDefaultMessage()),
(json, toMerge) -> {
json.setAll(toMerge);
return json;
}
));
}

public String getRedirect() {
return redirect;
}

public TreeNode getErrors() {
return errors;
}
}

这将被序列化为

{
"redirect": "...",
"errors": {
"field1": "err field1",
"field2": "err field2",
"field3": "err field3"
}
}
<小时/>

或者,如果您愿意,也可以使用通常的 Map<String, String>解决方案。

public class StringResponseDTO {
private String redirect;
private Map<String, String> errors;

public StringResponseDTO(final String redirect) {
this.redirect = redirect;
}

public StringResponseDTO(final Collection<? extends FieldError> errors) {
this.errors =
errors.stream()
.collect(Collectors.toMap(
FieldError::getField,
FieldError::getDefaultMessage
));
}

public String getRedirect() {
return redirect;
}

public Map<String, String> getErrors() {
return errors;
}
}

这会输出相同的内容

{
"redirect": "...",
"errors": {
"field1": "err field1",
"field2": "err field2",
"field3": "err field3"
}
}
<小时/>

这取决于你。

关于java - 返回带有键值对的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com