- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert XML to JSON array in Java?
A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array.
Syntax
public static JSONObject toJSONObject(java.lang.String string) throws JSONException
In the below example, converting XML to JSON array
Example
import org.json.*; public class ConvertXMLToJSONArrayTest { public static String xmlString= "<?xml version=\"1.0\" ?><root><test attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>"; public static void main(String[] args) { try { JSONObject json = XML.toJSONObject(xmlString); // converts xml to json String jsonPrettyPrintString = json.toString(4); // json pretty print System.out.println(jsonPrettyPrintString); } catch(JSONException je) { System.out.println(je.toString()); } } }
Output
{"root": {"test": [ { "attrib": "jsontext1", "content": "tutorialspoint" }, { "attrib": "jsontext2", "content": "tutorix" } ]}}
Advertisements