【问题标题】:Java spring boot - returning a json responseJava spring boot - 返回一个json响应
【发布时间】:2018-02-13 04:51:33
【问题描述】:

我想为新的 Java Spring Boot 应用程序创建自定义 json 响应。目前我只想创建一个虚拟 json 对象——开始控制输出 json 响应的结构。

当我这样做时,它想为 .puts 创建强制转换前缀——我曾经使用 Mongodb——BasicDBObject——但现在我这里没有 mongo。

 DBObject obj = new BasicDBObject();
 obj.put( "foo", "bar" );

我该怎么做?

--

@RequestMapping(value = "/login", method = RequestMethod.GET)
@CrossOrigin(origins = {"*"})
public ResponseEntity<?> login(
        @RequestParam(value="email", required=false, defaultValue="email") String email,
        @RequestParam(value="password", required=false, defaultValue="password") String password, 
        HttpServletRequest request
        ) throws  Exception {

                Object response = new Object();
                    response.put("information", "test");
                    response.put("id", 3);
                    response.put("name", "course1");

                return new ResponseEntity<>(response, HttpStatus.OK);
        }

【问题讨论】:

  • 最好使用有意义的对象,但您可以返回Map
  • _ 哈希映射?我安装了依赖 --- json-simple --- JSONObject response = new JSONObject(); response.put("name", "mkyong.com"); response.put("年龄", new Integer(100));
  • 我认为这个链接:stackoverflow.com/questions/44839753/… 会帮助你。

标签: java json spring


【解决方案1】:
**@ResetController**   // add this
public class YourClass{

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @CrossOrigin(origins = {"*"})
    public ResponseEntity<?> login(){
        Object response = new Object();
                    response.put("information", "test");
                    response.put("id", 3);
                    response.put("name", "course1");

        return new ResponseEntity<>(response, HttpStatus.OK);
     }
}

【讨论】:

  • 你的意思是“@RestController”——它说它在这个位置是不允许的。
  • 我已经安装了依赖项 com.googlecode.json-simplejson-simple - 让它与 JSONObject response = new JSONObject( ); response.put("name", "mkyong.com"); response.put("年龄", new Integer(100));
猜你喜欢
  • 2019-07-27
  • 2017-02-17
  • 2021-02-20
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 2017-12-04
  • 2021-04-25
  • 1970-01-01
相关资源
最近更新 更多