为什么使用Jersey在JSON中使用@返回名称

我使用的是JAXB,它是Jersey JAX-RS的一部分。 当我为输出类型请求JSON时,我的所有属性名称都以这样的星号开头,

这个对象;

package com.ups.crd.data.objects; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; @XmlType public class ResponseDetails { @XmlAttribute public String ReturnCode = ""; @XmlAttribute public String StatusMessage = ""; @XmlAttribute public String TransactionDate =""; } 

成为这个,

  {"ResponseDetails":{"@transactionDate":"07-12-2010", "@statusMessage":"Successful","@returnCode":"0"} 

那么,为什么名字中有@?

使用@XmlAttribute映射的任何属性都将在JSON中以“@”为前缀。 如果要删除它,只需使用@XmlElement注释您的属性。

大概这是为了避免潜在的名称冲突:

 @XmlAttribute(name="foo") public String prop1; // maps to @foo in JSON @XmlElement(name="foo") public String prop2; // maps to foo in JSON 

如果您正在编组XML和JSON,并且您不需要它作为XML版本中的属性,那么建议使用@XmlElement是最好的方法。

但是,如果它需要是XML版本中的属性(而不是元素),那么您确实有一个相当简单的替代方案。

您可以轻松设置JSONConfiguration ,以关闭“@”的插入。

它看起来像这样:

 @Provider public class JAXBContextResolver implements ContextResolver { private JAXBContext context; public JAXBContextResolver() throws Exception { this.context= new JSONJAXBContext( JSONConfiguration .mapped() .attributeAsElement("StatusMessage",...) .build(), ResponseDetails.class); } @Override public JAXBContext getContext(Class objectType) { return context; } } 

这里还有一些其他替代文件:

http://jersey.java.net/nonav/documentation/latest/json.html

您必须将JAXBContext配置中的JSON_ATTRIBUTE_PREFIX设置为"" ,默认情况下为"@"

 properties.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "");