使用这个answer作为提示,我为 /greetings
开发了一个 Spring Boot Controller ,以 JSON 格式返回不同语言的问候语。
当我以我想要的格式(对象数组)获得输出时,您能否让我知道是否有更好的方法?
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
@RestController
public class GreetingController {
@GetMapping("/greetings")
public HashMap<String, Object> getGreeting() {
ArrayList<Object> al = new ArrayList<Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("en", "Greetings!");
al.add(map1);
HashMap<String, String> map2 = new HashMap<>();
map2.put("hi", "Namaste!");
al.add(map2);
//
HashMap<String, Object> finalMap = new HashMap<>();
finalMap.put("all", al);
return finalMap;
}
}
收到(有效)输出:
{
"all": [
{
"en": "Greetings!"
},
{
"hi": "Namaste!"
}
]
}
最佳答案
如果您只需要对象数组,则不应选择映射,而应使用 List
类型。例如,如果您有 Greeting 对象并且想要返回所有问候语的列表,您的 GetMapping
将如下所示:
@GetMapping("/greetings")
public ResponseEntity<List<Map<String,String>>> getGreeting() {
ArrayList<Object> al = new ArrayList<Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("en", "Greetings!");
al.add(map1);
HashMap<String, String> map2 = new HashMap<>();
map2.put("hi", "Namaste!");
al.add(map2);
return ResponseEntity.ok(al);
}
使用 ResponseEntity
可确保您返回正确的状态代码,并且由于它包装了您的响应,因此更易于维护。
编辑:对于使用 map 创建的键值对,您可以使用 POJO。
class Greeting{
private String greetingLangCode;
private String greetingText;
// getters and setters
@JsonValue
public String info(){
return this.greetingLangCode + ":" + "greetingText";
}
}
此端点更改为
@GetMapping("/greetings")
public ResponseEntity<List<Greeting>> getGreeting() {
List<Greeting> al = new ArrayList<>();
al.add(new Greeting("en", "Greetings!"));
al.add(new Greeting("hi", "Namaste!"));
return ResponseEntity.ok(al);
}
但如果上述方法不起作用,您将需要一个自定义序列化程序来序列化 map 的 key:value
对。
可能this帖子很有帮助。这篇文章提供了如何编写自定义序列化器
和反序列化器
的完整示例。
关于java - Spring Boot - 返回带有对象数组的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58388703/