2012-10-28 44 views
0

我用这一个JAXB bean来JSON代码转换:JAXB与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(); 
} 

我的书类,输出结果是:

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

然而,我所要的输出与新泽西兼容:

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

如何使用上面的代码存档第二个JSON表示法并摆脱根元素?

我的解决办法:

切换到杰克逊现在,那里,你可以为root去包裹的选项。不过,如果有任何问题,我仍然对Jettison解决方案感兴趣。

回答

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); 
} 

}

+0

NAAA,这是行不通的。当然,它可以用于编组,但解组将会失败。我正在寻找“内部”Jettison的解决方案。 – user1438038