2012-10-28 46 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