8

I am using the JAXB that is part of the Jersey JAX-RS. When I request JSON for my output type, all my attribute names start with an asterisk like this,

This object;

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 ="";
}

becomes this,

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

So, why are there @ in the name?

bdoughan
  • 147,609
  • 23
  • 300
  • 400
John
  • 1,852
  • 4
  • 26
  • 49

3 Answers3

9

Any properties mapped with @XmlAttribute will be prefixed with '@' in JSON. If you want to remove it simply annotated your property with @XmlElement.

Presumably this is to avoid potential name conflicts:

@XmlAttribute(name="foo") public String prop1;  // maps to @foo in JSON
@XmlElement(name="foo") public String prop2;  // maps to foo in JSON
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • It's not working for me! with `@XmlAttribute` I get @ before fields and with `@XmlElement` I don't get any output! – sajjadG Feb 12 '14 at 20:54
1

If you are marshalling to both XML and JSON, and you don't need it as an attribute in the XML version then suggestion to use @XmlElement is the best way to go.

However, if it needs to be an attribute (rather than an element) in the XML version, you do have a fairly easy alternative.

You can easily setup a JSONConfiguration that turns off the insertion of the "@".

It would look something like this:

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
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;
}
}

There are also some other alternatives document here:

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

DaBlick
  • 898
  • 9
  • 21
  • Link is broken. and I checked the latest jersey documentation and there is nothing about `JSONConfiguration` in it! – sajjadG Feb 12 '14 at 20:56
0

You have to set JSON_ATTRIBUTE_PREFIX in your JAXBContext configuration to "" which by default is "@":

properties.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, ""); 
Marek Raki
  • 3,056
  • 3
  • 27
  • 50