0

これを使用して、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}

上記のコードで 2 番目の JSON 表記をアーカイブし、ルート要素を取り除くにはどうすればよいですか?

私の解決策:

Jackson に切り替えて、ルート アンラップのオプションを設定できます。ただし、Jettison ソリューションがあれば、まだ興味があります。

4

1 に答える 1

0

Book クラスの文字列出力を操作して、最初の { と 2 番目の { の間のすべてを削除できます。ここにそれを行う方法があります

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

}

于 2012-10-29T18:07:33.830 に答える