Необходимо преобразовать XML в Json в JavaJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Необходимо преобразовать XML в Json в Java

Сообщение Anonymous »

При преобразовании XML в JSON с помощью XML.toJSONObject я столкнулся с проблемой потери ведущих нулей. Я пытался использовать другую версию библиотеки org.json, но это было бесполезно.
Поэтому я написал другой код.

Код: Выделить всё

 LOGGER.debug("Starting the string to XML conversion");

String xml ="
0200Originally published in a slightly different form in the United Kingdom by Bloomsbury in 1998.0300Award-winning artist Jim Kay illustrates year two of Harry Potter's adventures at Hogwarts, in a stunning, gift-ready format.<p></p>The Dursleys were so mean and hideous that summer that all Harry Potter wanted was to get back to the Hogwarts School for Witchcraft and Wizardry. But just as he's packing his bags, Harry receives a warning from a strange, impish creature named Dobby who says that if Harry Potter returns to Hogwarts, disaster will strike.And strike it does. For in Harry's second year at Hogwarts, fresh torments and horrors arise, including an outrageously stuck-up new professor, Gilderoy Lockhart, a spirit named Moaning Myrtle who haunts the girls' bathroom, and the unwanted attentions of Ron Weasley's younger sister, Ginny.But each of these seem minor annoyances when the real trouble begins, and someone -- or something -- starts turning Hogwarts students to stone. Could it be Draco Malfoy, a more poisonous rival than ever? Could it possibly be Hagrid, whose mysterious past is finally told? Or could it be the one everyone at Hogwarts most suspects... Harry Potter himself?0600"Seeing Jim Kay's illustrations moved me profoundly. I love his interpretation of Harry Potter's world, and I feel honored and grateful that he has lent his talent to it." -- J.K. Rowling1200Jim Kay won the Kate Greenaway Medal in 2012 for his illustrations in <i>A Monster Calls</i> by Patrick Ness. Jim studied illustration at the University of Westminster and since graduating has worked in the archives of Tate Britain and the Royal Botanic Gardens at Kew. Jim has produced concept work for television and contributed to a group exhibition at the Victoria and Albert Museum in London. He now lives and works in Northamptonshire, England, with his wife. <br/> <p>J.K. ROWLING is the author of the enduringly popular, era-defining Harry Potter seven-book series, which have sold over 600 million copies in 85 languages, been listened to as audiobooks for over one billion hours and made into eight smash hit movies. To accompany the series, she wrote three short companion volumes for charity, including <i>Fantastic Beasts and Where to Find Them</i>, which went on to inspire a new series of films featuring Magizoologist Newt Scamander. Harry's story as a grown-up was continued in a stage play, <i>Harry Potter and the Cursed Child</i>, which J.K. Rowling wrote with playwright Jack Thorne and director John Tiffany.</p></p><p></p> <p>In 2020, she returned to publishing for younger children with the fairy tale <i>The Ickabog</i>, the royalties for which she donated to her charitable trust, Volant, to help charities working to alleviate the social effects of the Covid 19 pandemic. Her latest children's novel, <i>The Christmas Pig</i>, was published in 2021.</p></p><p></p> <p>J.K. Rowling has received many awards and honours for her writing, including for her detective series written under the name Robert Galbraith. She supports a wide number of humanitarian causes through Volant, and is the founder of the international children's care reform charity Lumos. J.K.  Rowling lives in Scotland with her family.</p></p>";

// Create an XmlMapper to parse XML
XmlMapper xmlMapper = new XmlMapper();

// Read XML into a JsonNode
JsonNode jsonNode = xmlMapper.readTree(xml.getBytes());

// Create an ObjectMapper for JSON
ObjectMapper objectMapper = new ObjectMapper();

// Convert JsonNode to JSON string
String jsonString = objectMapper.writeValueAsString(jsonNode);
Это решает основную проблему нуля, но не преобразует весь XML в JSON. Например, если в одном атрибуте имеется 4 объекта, преобразуется только один объект. Я не понимаю, как это исправить.
Для приведенной выше строки XML в выходных данных получено только следующее:

Код: Выделить всё

"titledetail": {
"b202": "01",
"titleelement": {
"x409": "01",
"x501": null,
"b031": "Harry Potter and the Chamber of Secrets: The Illustrated Edition (Harry Potter, Book 2)",
"b029": "Volume 2"
}
}

Как решить эту проблему? Как преобразовать все атрибуты в JSON?

Подробнее здесь: https://stackoverflow.com/questions/788 ... on-in-java
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»