【发布时间】:2020-02-11 18:46:33
【问题描述】:
使用answer 作为提示,我为/greetings 开发了一个 Spring Boot 控制器,以 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!"
}
]
}
【问题讨论】:
标签: java json rest spring-boot