1. 程式人生 > >spring接受複雜json引數,轉化為物件

spring接受複雜json引數,轉化為物件

我們在springmvc要接受一個複雜的引數,但是不知道怎麼接受這個複雜的引數,那我們可以返回這個引數,這樣就知道怎麼寫請求引數

例如我要一個json字串引數,引數是一個物件,一個物件包含2個物件,包含一個user和localauth物件

	@ResponseBody
	@RequestMapping(value="/registerOrdinaryUser",method = RequestMethod.GET)
	public UserVo registerOrdinaryUser(){	
		UserVo userVo = new UserVo();
		Localauth localauth = new Localauth();
		localauth.setUsername("jacket");
		User user = new User();
		user.setSex("男");
		userVo.setLocalauth(localauth);
		userVo.setUser(user);
		return userVo;
	}

返回json

{
  "localauth": {
    "id": null,
    "userId": null,
    "username": "jacket",
    "email": null,
    "password": null
  },
  "user": {
    "userId": null,
    "status": null,
    "name": null,
    "sex": "男",
    "role": null,
    "birthday": null,
    "regdate": null,
    "phone": null,
    "head": null
  }
}


這樣就知道請求引數怎麼寫了。

下面測試一下。

	@ResponseBody
	@RequestMapping(value="/registerOrdinaryUser",method = RequestMethod.GET)
	public UserVo registerOrdinaryUser(@RequestBody UserVo userVo){	
		return userVo;
	}


傳遞引數,確認返回的引數是否接受,

請求引數

{
    "localauth": {
        "username": "struts",
        "password": 123,
        "email": ""
    },
    "user": {
        "sex": "男"
    }
}
返回引數
{
  "localauth": {
    "id": null,
    "userId": null,
    "username": "struts",
    "email": "",
    "password": "123"
  },
  "user": {
    "userId": null,
    "status": null,
    "name": null,
    "sex": "男",
    "role": null,
    "birthday": null,
    "regdate": null,
    "phone": null,
    "head": null
  }
}