request 獲取 JSON 數據流

request 獲取 JSON 數據流

  • HttpServletRequest對象獲取
  •  request.getInputStream() 獲取 JSON 數據流

JSONObject jsonObject = null;
		try {
			BufferedReader streamReader = new BufferedReader( new InputStreamReader( request.getInputStream(), "UTF-8" ) );
			StringBuilder respomseStrBuilder = new StringBuilder();
			String inputStr = "";
			while ((inputStr = streamReader.readLine())!= null){
				respomseStrBuilder.append( inputStr );
			}
			jsonObject = JSONObject.parseObject( respomseStrBuilder.toString() );
			logger.info( "syncAuthUser AccountDTO JSON = {}",jsonObject );
		}catch (Exception e){
			e.printStackTrace();
		}
  • @RequestBody 註解獲取
  • 注意JSONObject、JSONArray、實體類數據類型
  • 以下兩種方法均可
@ApiOperation(value = "jSON參數獲取", notes = "jSON參數獲取",produces = "application/json;charset=UTF-8")
    @GetMapping(value = "/getJSON")
    public String getJSON (
            @RequestBody JSONObject s
    ){
//        String s = "Name: = " + name + ",Age:" + age + ",Email:" + email;

        System.out.println(s);
        System.out.println( s.getString( "name" ) );
        System.out.println( s.getInteger( "age" ) );
        System.out.println( s.getString( "email" ) );
        return s.toJSONString();
    }

 

@ApiOperation(value = "jSON參數獲取", notes = "jSON參數獲取",produces = "application/json;charset=UTF-8")
    @GetMapping(value = "/getJSON")
    public String getJSON(
            @RequestBody JSONpojo pojo
    ){

        System.out.println(pojo);
        System.out.println( pojo.getName() );
        System.out.println( pojo.getAge() );
        System.out.println( pojo.getEmail() );
        JSONObject jsonObject = new JSONObject();
        jsonObject.put( "data",pojo );
        return jsonObject.toJSONString();
    }
  • postman 測試

隨筆記錄,方便學習

2019-07-08

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章