Quick and Efficient XML to JSON Conversion in Java
When working with XML and JSON data, the need to convert between the two formats often arises. Here are some effective tools and methods for achieving quick and seamless XML to JSON conversions in Java:
1. JSON in Java Library:
The JSON in Java library provides a convenient solution for XML conversion. Its XML class includes the toJSONObject() method, which converts XML strings or objects into JSON objects. Maven dependency:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency>
2. Jackson Library:
The Jackson library is another popular choice for working with XML and JSON. It includes specialized modules for XML processing, such as the jackson-dataformat-xml module. The following code snippet demonstrates XML to JSON conversion using Jackson:
import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.databind.JsonNode; public class JacksonExample { public static void main(String[] args) throws IOException { String xml = "<test attrib=\"moretest\">Turn this to JSON</test>"; XmlMapper xmlMapper = new XmlMapper(); JsonNode jsonNode = xmlMapper.readTree(xml); String json = xmlMapper.writeValueAsString(jsonNode); System.out.println(json); } }
3. JAXB (Java Architecture for XML Binding):
JAXB is a framework that provides a convenient way to bind XML to Java objects. While it primarily focuses on generating XML from Java objects, it can also be used for the reverse process. The following code sample shows how to convert XML to JSON using JAXB:
import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import com.google.gson.Gson; public class JaxbExample { public static void main(String[] args) throws Exception { String xml = "<test attrib=\"moretest\">Turn this to JSON</test>"; JAXBContext context = JAXBContext.newInstance(Test.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Test test = (Test) unmarshaller.unmarshal(new StringReader(xml)); Gson gson = new Gson(); String json = gson.toJson(test); System.out.println(json); } }
The above is the detailed content of How Can I Quickly and Efficiently Convert XML to JSON in Java?. For more information, please follow other related articles on the PHP Chinese website!