Java Tutorials
Abstraction in Java | Abstract Class & Method with Example
What is Abstraction in Java? Abstraction in JAVA shows only the essential attributes and hides...
JSON is an abbreviation for Javascript Object Notation, which is a form of data that follows a certain rule that most programming languages are currently readable. We can easy to save it to a file or record in the database. JSON format uses key-value pairs to describe data.
In following the example, we define a JSON string that stores personal information:
{
"username" : "guru99user",
"email" : "This email address is being protected from spambots. You need JavaScript enabled to view it."
}
So the syntax of JSON is very simple. Each data information will have two parts: key and value which correspond to the field name and its value in a certain record. But as further looking, there are a few things like this:
In this tutorial, you will learn
XML stands for eXtensible Markup Language also called the extensible markup language proposed by the World Wide Web Consortium (http://www.w3.org/) to create other markup languages. This is a simple subset that can describe many different types of data, so it is very useful in sharing data between systems.
Tags in XML are often not predefined, but they are created according to user conventions. XML introduces new features based on the advantages of HTML.
There are some more useful XML-making features in diverse systems and solutions:
XML is built on a nested node structure. Each node will have an opening tag and a closing tag as follows:
<node>content</node>
In which:
At the top of each XML file you must declare a tag to indicate the version XML is in use. The syntax of the instruction tag:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Gson (https://github.com/google/gson) is a java library that allows users to convert from a Java object to JSON string and also convert from a JSON string to Java object. Gson can work with arbitrary Java objects including existing objects without you having their source-code.
Since version 1.6, Gson introduces two new classes – JsonReader and JsonWriter to provide streaming processing on JSON data.
JsonWriter writer = new JsonWriter(); writer.beginObject(); writer.name("key").value("value"); writer.endObject();
JsonReader reader = new JsonReader(); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("key")) { String value = reader.nextString(); } } reader.endObject();
Gson streaming processing is fast. However you need to handle each pair (key => value) of processing JSON data.
JAXB stands for Java Architecture for XML Binding, which is a library that uses annotations to convert Java objects to XML content and vice versa. As JAXB is defined via a specification, we can use different implementations for this standard.
With JAXB, we often use following basic annotations, namely:
The syntax for general implementation is as follows. First, we will initialize the JAXBContext object with the MyObject object to convert.
JAXBContext jaxbContext = JAXBContext.newInstance(MyObject.class);
In this JAXBContext object, it has a method to create an object that converts XML content to a Java object, Unmarshaller.
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
In this JAXBContext object, it has a method to create the object that converts the Java object to the XML content that is Marshaller.
Marshaller marshallerObj = jaxbContext.createMarshaller();
We implement the example of XML - JSON conversion on the platform:
Step 1. Create a new Java Project.
Step 2. Set Project name is XmlToJsonExample.
Step 3. Create folder data/input containing two file sample.xml and sample.json.
Let's first define our XML with department, role and person properties.
The general architechture is: <one department – many roles> ; <one role – many persons>.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <root> <department> <roles> <role id="1"> <position>head</position> <salary>10k</salary> </role> <role id="2"> <position>manager</position> <salary>8k</salary> </role> <role id="3"> <position>employee</position> <salary>5k</salary> </role> </roles> <persons> <person id="1"> <name>Red</name> <role>1</role> </person> <person id="2"> <name>Green</name> <role>2</role> </person> <person id="3"> <name>Blue</name> <role>2</role> </person> <person id="4"> <name>Yellow</name> <role>3</role> </person> <person id="5"> <name>Brown</name> <role>3</role> </person> </persons> </department> </root>
Secondly, we define JSON having the same idea:
{ "roles": [ { "id": "1", "position": "head", "salary": "10k", "persons": [ { "id": "1", "name": "Red" } ] }, { "id": "2", "position": "manager", "salary": "8k", "persons": [ { "id": "2", "name": "Green" }, { "id": "3", "name": "Blue" } ] }, { "id": "3", "position": "employee", "salary": "5k", "persons": [ { "id": "4", "name": "Yellow" }, { "id": "5", "name": "Brown" } ] } ] }
Step 4. Define corresponding object classes in the package model.
@XmlRootElement(name = "role") public class Role { private String id; private String position; private String salary; public Role() { super(); } public Role(String id, String position, String salary) { super(); this.id = id; this.position = position; this.salary = salary; } @XmlAttribute(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlElement(name = "position") public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @XmlElement(name = "salary") public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } }
@XmlRootElement(name = "person") public class Person { private String id; private String name; private String role; public Person() { super(); } public Person(String id, String name, String role) { super(); this.id = id; this.name = name; this.role = role; } @XmlAttribute(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlElement(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name = "role") public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
@XmlRootElement(name = "department") public class Department { private List<Role> roles; private List<Person> persons; public Department() { super(); } public Department(List<Role> roles, List<Person> persons) { super(); this.roles = roles; this.persons = persons; } @XmlElementWrapper(name = "roles") @XmlElement(name = "role") public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } @XmlElementWrapper(name = "persons") @XmlElement(name = "person") public List<Person> getPersons() { return persons; } public void setPersons(List<Person> persons) { this.persons = persons; } }
XMLModel.java:
@XmlRootElement(name = "root") public class XMLModel { private Department department; public XMLModel() { super(); } public XMLModel(Department department) { super(); this.department = department; } @XmlElement(name = "department") public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
Step 5. Set up library Gson 2.8.5.
Firstly, we define performing classed in package service.
At the first step of the first process, we use technique Un-marshalling of JAXB.
Un-marshalling provides a client application the ability to convert XML data into JAXB derived Java objects.
We define function getObjectFromXmlFile to un-marshal our XML file back to a Java object. This function is defined in class XMLService.
public XMLModel getObjectFromXmlFile(String filePath) { try { File file = new File(filePath); JAXBContext jaxbContext = JAXBContext.newInstance(XMLModel.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); XMLModel root = (XMLModel) jaxbUnmarshaller.unmarshal(file); return root; } catch (JAXBException e) { e.printStackTrace(); return null; } }
We call the code above in class XmlToJsonService.
XMLService xmlService = new XMLService(); XMLModel xmlModel = xmlService.getObjectFromXmlFile(filePathIn); Department department = xmlModel.getDepartment(); List<Role> roles = department.getRoles(); List<Person> persons = department.getPersons();
Then we go to next step.
At this step, we define function writeDataToJsonFile to write data to the JSON file. This function is defined in class JsonService.
Note that to write a list of JSON strings, we use the function beginArray() and endArray(). Between these two functions, we write each JSON string.
public void writeDataToJsonFile(String filePath, List<Role> roles, List<Person> persons) { try { JsonWriter writer = new JsonWriter(new FileWriter(filePath)); writer.setIndent(" "); writer.beginObject(); writer.name("roles"); writer.beginArray(); for (Role role : roles) { writer.beginObject(); writer.name("id").value(role.getId()); writer.name("position").value(role.getPosition()); writer.name("salary").value(role.getSalary()); writer.name("persons"); writer.beginArray(); for (Person person : persons) { if (person.getRole().equalsIgnoreCase(role.getId())) { writer.beginObject(); writer.name("id").value(person.getId()); writer.name("name").value(person.getName()); writer.endObject(); } } writer.endArray(); writer.endObject(); } writer.endArray(); writer.endObject(); writer.close(); } catch (IOException e) { } }
We call the above code in class XmlToJsonService.
JsonService jsonService = new JsonService(); jsonService.writeDataToJsonFile(filePathOut, roles, persons);
That's the first process.
At the first step of second process, we define function getDataFromJsonFile to read data from JSON file. This function is defined in class JsonService.
Note that to read a list of JSON strings, we use the function beginArray() and endArray(). Between these two functions, we read each JSON string.
public void getDataFromJsonFile(String filePath, List<Role> roles, List<Person> persons) { try { JsonReader reader = new JsonReader(new FileReader(filePath)); reader.beginObject(); while (reader.hasNext()) { String nameRoot = reader.nextName(); if (nameRoot.equals("roles")) { reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); Role role = new Role(); while (reader.hasNext()) { String nameRole = reader.nextName(); if (nameRole.equals("id")) { role.setId(reader.nextString()); } else if (nameRole.equals("position")) { role.setPosition(reader.nextString()); } else if (nameRole.equals("salary")) { role.setSalary(reader.nextString()); } else if (nameRole.equals("persons")) { reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); Person person = new Person(); person.setRole(role.getId()); while (reader.hasNext()) { String namePerson = reader.nextName(); if (namePerson.equals("id")) { person.setId(reader.nextString()); } else if (namePerson.equals("name")) { person.setName(reader.nextString()); } } persons.add(person); reader.endObject(); } reader.endArray(); } } roles.add(role); reader.endObject(); } reader.endArray(); } } reader.endObject(); reader.close(); } catch (IOException e) { } }
We call the above code in class XmlToJsonService.
JsonService jsonService = new JsonService(); List<Role> roles = new ArrayList<>(); List<Person> persons = new ArrayList<>(); jsonService.getDataFromJsonFile(filePathIn, roles, persons);
JSON to XML in JAVA is converted by using JSONObject json = new JSONObject(str); String xml = XML. If you have a valid dtd file or the xml file then it is very easy to transform json to xml and also xml to json.
Then we go to next step.
At this step, we use technique Marshalling of JAXB.
Marshalling provides a client application the ability to convert a JAXB derived Java object tree into XML data.
We define function parseObjectToXm to marshall Java object to XML message. This function is defined in class
XMLService. public void parseObjectToXml(String filePath, XMLModel xmlModel) { try { JAXBContext contextObj = JAXBContext.newInstance(XMLModel.class); Marshaller marshallerObj = contextObj.createMarshaller(); marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshallerObj.marshal(xmlModel, new FileOutputStream(filePath)); } catch (JAXBException je) { System.out.println("JAXBException"); } catch (IOException ie) { System.out.println("IOException"); } }
We call the above code in class XmlToJsonService.
XMLService xmlService = new XMLService(); XMLModel xmlModel = new XMLModel(); Department department = new Department(); department.setRoles(roles); department.setPersons(persons); xmlModel.setDepartment(department); xmlService.parseObjectToXml(filePathOut, xmlModel);
That's the second process.
In this tutorial, we briefly learned one way in which JAXB can read XML data and Gson write it to JSON. On the contrary, we also saw the way that Gson read JSON data and JAXB write it to XML.
This article is contributed by David Howard
What is Abstraction in Java? Abstraction in JAVA shows only the essential attributes and hides...
Download PDF 1) Explain what is Groovy? Groovy is an object-oriented programming language for JVM...
What is TypeScript? TypeScript is a superset of JavaScript. TypeScript is pure object-oriented...
Example#1: JavaScript Multiplication Table Create a simple multiplication table asking the user...
What is Spring Framework? Spring Framework is an open-source framework for building web...
What is Constructor in Java? CONSTRUCTOR is a special method that is used to initialize a newly...