我正在休息时使用springmvc,我有2个项目,一个是web层,另一个是rest层。
现在我有一个患者对象有一组地址和contactinfo,现在我正在尝试创建患者的Json对象并通过REST请求发送它,但是在REST服务层我无法获取地址和联系人设置。< / p>
当我尝试调试REST层上的json对象时&amp;它看起来像:
{
"myHashMap":{
"disease":"fever",
"bloodGroup":"O",
"contactInfo":{
"myArrayList":[
{
"myHashMap":{
"contactInfoId":1,
"fixedLineNo":"fixedline",
"mobileNo":"mobile",
"faxNo":"faxno",
"emailId":"1@msn.com",
"organisationId":101,
"locationId":800,
"createDate":"Apr 2, 2015 2:01:53 PM",
"updateDate":"Apr 2, 2015 2:01:53 PM",
"updateUserId":"meenakshi",
"createUserId":"rahul",
"status":true
}
}
]
},
"adressess":{
"myArrayList":[
{
"myHashMap":{
"addressId":100,
"city":"indore"
}
}
]
}
}
}
我在控制器层创建的json对象如下:
Patient patient = new Patient();
Gson gson = new Gson();
ContactInfo contactInfo = new ContactInfo();
Address address = new Address();
contactInfo.setContactInfoId(1l);
contactInfo.setCreateDate(new Date());
contactInfo.setCreateUserId("rahul");
contactInfo.setEmailId("1@msn.com");
contactInfo.setFaxNo("faxno");
contactInfo.setFixedLineNo("fixedline");
contactInfo.setLocationId(800l);
contactInfo.setMobileNo("mobile");
contactInfo.setOrganisationId(101l);
contactInfo.setStatus(true);
contactInfo.setUpdateDate(new Date());
contactInfo.setUpdateUserId("meenakshi");
patient.setBloodGroup("O");
patient.setDisease("fever");
address.setAddressId(100l);
address.setCity("indore");
List<ContactInfo> contactInfosList = new ArrayList<ContactInfo>();
contactInfosList.add(contactInfo);
List<Address> addressList = new ArrayList<Address>();
addressList.add(address);
patient.setAdressess(new HashSet<Address>(addressList));
patient.setContactInfo(new HashSet<ContactInfo>(contactInfosList));
String patientJsonString = gson.toJson(patient);
JSONObject patientJsonObj = null;
try {
patientJsonObj = new JSONObject(patientJsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return patientJsonObj;
REST层使用的代码如下:
Patient pat = gson.fromJson(patientJsonDto.toString(), Patient.class);
但我无法通过其中的地址和联系信息检索患者对象。
提前致谢。
答案 0 :(得分:0)
Juste使用类似的东西:
@RestController
@RequestMapping("/api")
public class PatientResource {
@RequestMapping(
value = "/rest/patient/{id}",
method = RequestMethod.GET,
headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> producePatient(@PathVariable("id") Long id) {
final HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
try{
Patient patient = Patient.findById(id);
return new ResponseEntity<Patient >(patient , headers, HttpStatus.OK);
} catch (Exception e) {
log.error("Error >>> ",e);
return new ResponseEntity<String>("{\"ERROR\":\""+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
确保您拥有图书馆杰克逊:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
在你的类路径中,spring默认会为所有@ResponseBody使用它,并且会为你执行从/到json的转换。
希望这会对你有所帮助