简体   繁体   中英

JSON serialization in Jersey - How to ignore XmlJavaTypeAdapter for serializing a map?

In my Jersey-based REST webservice I need to provide xml and json output. The class Result has a map, annotated with XmlJavaTypeAdapter to correctly serialize it to xml.

@XmlRootElement
public class Result {

    private Map<String,Integer> results = new HashMap<String, Integer>();

    public Result(){}

    @XmlJavaTypeAdapter(ResultMapAdapter.class)
    public Map<String,SearchResult> getResults() {
        return results;
    }
}

The XML output looks like:

<results>
  <result><name>Key1</name><value>Value1</value>
  <result><name>Key2</name><value>Value2</value>
</results>

And the json output looks like

  "result":[{
    "name": "Key1",
    "value": Value1
  },{
    "name": "Key2",
    "value": Value2
  }]

But I want that it looks like:

  "result":{
    "Key1": Value1,
    "Key2": Value2
  }

If I remove the XMlRootElement and the XmlJavaTypeAdapter annotation, the json output looks like I wanted, but then the xml serialization failed. Is there a workaround?

One possible solution is the use an custom ObjectMapperProvider. The Following provider doesn't create an combined mapper for json and xml. So the json serialization doesn't use the xml annoatation.

Of course the disadvantage of this sol

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;

    public ObjectMapperProvider() {
        defaultObjectMapper = createDefaultMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {

        return defaultObjectMapper;
    }


    private static ObjectMapper createDefaultMapper() {

        ObjectMapper result = new ObjectMapper();
        result.configure(Feature.INDENT_OUTPUT, true);

        return result;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM