REST - JSONrequest 映射到 Java 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17767610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
REST - JSONrequest mapping to a java object
提问by SaifDeen
I m trying to Map a little bigger JSON to a Java Object with nested objects. I m using a RESTful WS with Jersey Java.
我正在尝试将更大的 JSON 映射到带有嵌套对象的 Java 对象。我正在使用带有 Jersey Java 的 RESTful WS。
Heres a example of the JSON:
这是 JSON 的示例:
JSON is now without the user rootKeyPath:
JSON 现在没有用户 rootKeyPath:
{
"memberShip": {
"validTill": "2014-07-19T18:57:30Z",
"validSince": "2013-07-19T18:57:30Z"
},
"userID": "xxxxx",
"displayName": "xxxx",
"phoneNumber": "+xxx",
"country": {
"iso2DTO": "xxx",
"short_nameDTO": "xxx",
"calling_codeDTO": "+xxx",
"idNumberDTO": 009
},
"contacts": [
{
"phoneNumber": "xxxxxx",
"fullName": "xxxxx"
},
{
"phoneNumber": "xxxxxx",
"fullName": "xxxxx"
}
],
"device": {
"name": "xxxx",
"devToken": "xxxx",
"systemVersion": "x.x.x",
"model": "xxxx",
"systemName": "xxxx"
}
}
This is my POST receive methode:
这是我的 POST 接收方法:
@Path("/user/integrate")
public class IntegrateUser {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createUserAccount(User user){
return Response.status(201).build();
}
}
My User object:
我的用户对象:
@XmlRootElement(name = "user")
public class User {
private Integer ID;
@XmlElement(name = "displayName")
private String displayName;
@XmlElement(name = "phoneNumber")
private String phoneNumber;
@XmlElement(name = "status")
private String status;
@XmlElement(name = "userID")
private String userID;
@XmlElement(name = "country")
private Country country;
@XmlElement(name = "device")
private Device device;
@XmlElement(name = "memberShip")
private MemberShip memberShip;
@XmlElement(name = "contacts")
private List<Contact> contactsList;
/**
*
*/
public User() {
// TODO Auto-generated constructor stub
}
/**
* @return the iD
*/
public Integer getID() {
return ID;
}
/**
* @param iD the iD to set
*/
public void setID(Integer iD) {
ID = iD;
}
/**
* @return the displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* @param displayName the displayName to set
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* @return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* @param phoneNumber the phoneNumber to set
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the userID
*/
public String getUserID() {
return userID;
}
/**
* @param userID the userID to set
*/
public void setUserID(String userID) {
this.userID = userID;
}
/**
* @return the country
*/
public Country getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(Country country) {
this.country = country;
}
/**
* @return the device
*/
public Device getDevice() {
return device;
}
/**
* @param device the device to set
*/
public void setDevice(Device device) {
this.device = device;
}
/**
* @return the memberShip
*/
public MemberShip getMemberShip() {
return memberShip;
}
/**
* @param memberShip the memberShip to set
*/
public void setMemberShip(MemberShip memberShip) {
this.memberShip = memberShip;
}
/**
* @return the contactsList
*/
public List<Contact> getContactsList() {
return contactsList;
}
/**
* @param contactsList the contactsList to set
*/
public void setContactsList(List<Contact> contactsList) {
this.contactsList = contactsList;
}
}
So every time i send this request the following error appears:
所以每次我发送这个请求时都会出现以下错误:
Jul 19, 2013 9:58:00 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
org.codehaus.Hymanson.map.exc.UnrecognizedPropertyException: Unrecognized field "user" (Class de.wazzuup.server.ws.model.User), not marked as ignorable
at [Source: org.apache.catalina.connector.CoyoteInputStream@228190; line: 1, column: 10] (through reference chain: de.wazzuup.server.ws.model.User["user"])
So what i m doing wrong? I m not sure about the Contacts array mapping. Also about the Xml annotation. Its JSON, do I need the annotations? Please any advice would be great!!
那么我做错了什么?我不确定 Contacts 数组映射。还有关于 Xml 注释。它的 JSON,我需要注释吗?请任何建议都会很棒!!
Edit 1, exception stacktrace:
编辑 1,异常堆栈跟踪:
Jul 21, 2013 2:02:51 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
org.codehaus.Hymanson.map.JsonMappingException: No suitable constructor found for type [simple type, class de.wazzuup.server.ws.model.MemberShip]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: org.apache.catalina.connector.CoyoteInputStream@228190; line: 1, column: 16] (through reference chain: de.wazzuup.server.ws.model.User["memberShip"])
at org.codehaus.Hymanson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:740)
at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.Hymanson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.Hymanson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.Hymanson.map.ObjectMapper._readValue(ObjectMapper.java:2695)
at org.codehaus.Hymanson.map.ObjectMapper.readValue(ObjectMapper.java:1308)
at org.codehaus.Hymanson.jaxrs.HymansonJsonProvider.readFrom(HymansonJsonProvider.java:419)
at com.sun.jersey.json.impl.provider.entity.HymansonProviderProxy.readFrom(HymansonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:488)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
采纳答案by jgm
Your first problem is that your user object is one level down. If you can change your JSON input to be:
您的第一个问题是您的用户对象向下一级。如果您可以将 JSON 输入更改为:
{
"memberShip": {
"validTill": "2014-07-19T18:57:30Z",
"validSince": "2013-07-19T18:57:30Z"
},
...
}
That would solve the issue. Alternatively you could make a UserContainer
object which just contained the user and use that in the resource method.
这样问题就解决了。或者,您可以创建一个UserContainer
仅包含用户的对象并在资源方法中使用它。
You aren't showing your Contacts
class so I can't talk about that, however you should use List
rather than ArrayList
when referring to it in your User
.
你没有展示你的Contacts
课程,所以我不能谈论那个,但是你应该使用List
而不是ArrayList
在你的User
.