Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Xml to json conversion with sibling elements with the same tag #1348

Open
heitorbarbieri opened this issue Aug 22, 2023 · 0 comments
Open

Xml to json conversion with sibling elements with the same tag #1348

heitorbarbieri opened this issue Aug 22, 2023 · 0 comments

Comments

@heitorbarbieri
Copy link

json4s version

4.1.0-M2

scala version

2.13.11

jdk version

openjdk version "11.0.18" 2023-01-17

scenario

import org.json4s.Xml.toJson
import org.json4s.native.JsonMethods.render
import org.json4s.native.Printer.compact
import javax.xml.parsers.{SAXParser, SAXParserFactory}
import scala.xml.Elem

object Xml2Json extends App {
  val xml = """<?xml version="1.0" encoding="UTF-8"?>
              |<book>
              |   <title>Some title</title>
              |   <description>some description</description>
              |   <author>
              |      <id>1</id>
              |      <name>some author name</name>
              |   </author>
              |   <review>nice book</review>
              |   <review>this book sucks</review>
              |   <review>amazing work</review>
              |</book>""".stripMargin

  val factory: SAXParserFactory = javax.xml.parsers.SAXParserFactory.newInstance()
  val parser: SAXParser = factory.newSAXParser()
  val elem: Elem = scala.xml.XML.withSAXParser(parser).loadString(xml)
  val json: JObject = toJson(elem).asInstanceOf[JObject]
  val jsonStr: String = compact(render(json))

  println(jsonStr)
}

output

{"book":{"title":"Some title","description":"some description","author":{"id":"1","name":"some author name"},"review":"nice book","review":"this book sucks","review":"amazing work"}}

expected output

{"book":{"title":"Some title","description":"some description","author":{"id":"1","name":"some author name"},"review": ["nice book", "this book sucks", "amazing work"]}}

reason

RFC 7159 says:

When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant