0

I use this to convert a JAXB bean to JSON code:

private String marshall(final Book beanObject) throws Exception
{
  JAXBContext context = JAXBContext.newInstance(Book.class);
  Marshaller marshaller = context.createMarshaller();

  Configuration config = new Configuration();
  MappedNamespaceConvention con = new MappedNamespaceConvention(config);
  StringWriter jsonDocument = new StringWriter();
  XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(con, jsonDocument);
  marshaller.marshal(beanObject, xmlStreamWriter);

  return jsonDocument.toString();
}

For my Book class, the output is:

{"bookType":{"chapters":["Genesis","Exodus"],"name":"The Bible","pages":600}}

However, I want the output to be compatible with Jersey:

{"chapters":["Genesis","Exodus"],"name":"The Bible","pages":600}

How can I archive the second JSON notation with above code and get rid of the root element?

My solution:

Switched to Jackson now, there you can set an option for root unwrapping. I'm still interested in Jettison solutions, though, if there are any.

user1438038
  • 5,821
  • 6
  • 60
  • 94

1 Answers1

0

You can manipulate the string output of your Book class to remove everything between the first { and the second {. Here is how to do it

public class AdjustJSONFormat { 
public static void main(String[] args){
        String inputS = "{\"bookType\":{\"chapters\":" +
                "[\"Genesis\",\"Exodus\"]," +
                "\"name\":\"The Bible\",\"pages\":600}}";
        String result = pruneJson(inputS);
        System.out.print(result);
}

public static String pruneJson(String input){
    int indexOfFistCurlyBrace = input.indexOf('{', 1);      
    return input.substring(indexOfFistCurlyBrace, input.length()-1);
}

}

Abraham
  • 603
  • 7
  • 19
  • Naaa, that won't work. Sure, it does for marshalling, but unmarshalling will fail then. I was looking for a solution "inside" Jettison. – user1438038 Oct 30 '12 at 16:47