我用它来将JAXB bean转换为JSON代码:
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();
}
对于我的Book类,输出为:
{"bookType":{"chapters":["Genesis","Exodus"],"name":"The Bible","pages":600}}
但是,我希望输出与Jersey兼容:
{"chapters":["Genesis","Exodus"],"name":"The Bible","pages":600}
如何使用上面的代码存档第二个JSON表示法并删除根元素?
我的解决方案:
现在切换到杰克逊,在那里你可以设置一个根解包的选项。不过,如果有的话,我仍然对Jettison解决方案感兴趣。
答案 0 :(得分:0)
您可以操纵Book类的字符串输出,以删除第一个{和第二个{之间的所有内容。这是怎么做的
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);
}
}