0

Jackson XmlMapper を使用して XML 文字列を読み取り、それを JsonString に変換しています。私のXMLファイルは次のとおりです。

<root>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk105">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk114">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
</catalog>
</root>

変換用に書いたコードは次のとおりです。

XmlMapper xmlMapper = new XmlMapper();
List entries = xmlMapper.readValue(file, List.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(entries);

出力として取得しているJson文字列は次のとおりです。

{
  "id": "569df9c1e4b0e505eb9fb913",
  "json": [
    {
      "book": {
        "id": "bk114",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications \n          with XML."
      }
    }
  ],
  "fileType": "xml"
}

最後の本だけが Json 文字列にマップされています。 同様の質問への回答では、xml 文字列を一般的なリスト クラスではなくオブジェクト クラスに読み込むよう提案されています。しかし、私が処理しようとしている XML ファイルは一般的であり、POJO 表現が固定されていません。この問題を処理するにはどうすればよいですか?

ありがとう!

4

1 に答える 1

0

問題を解決しました。org.json.XML toJsonObject 関数を使用して、XML を JSON に変換しました。この XML パーサーは、問題のような複雑な XML ファイルを解析できます。

于 2016-02-04T03:49:04.550 に答える