Trending October 2023 # Convert Json To Xml Java Using Gson And Jaxb With Example # Suggested November 2023 # Top 15 Popular | Benhvienthammyvienaau.com

Trending October 2023 # Convert Json To Xml Java Using Gson And Jaxb With Example # Suggested November 2023 # Top 15 Popular

You are reading the article Convert Json To Xml Java Using Gson And Jaxb With Example updated in October 2023 on the website Benhvienthammyvienaau.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested November 2023 Convert Json To Xml Java Using Gson And Jaxb With Example

What is JSON?

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 easily 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", }

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:

The JSON string is enclosed by curly braces {}.

The keys and values of JSON must be enclosed in quotation marks {“}.

JSON keys should be unsigned letters or numbers, _, and no spaces, the first character should not be set to numbers.

What is XML?

There are some more useful XML-making features in diverse systems and solutions:

XML is extensible: XML allows you to create your own custom tags to suit your application.

XML carries data, not displaying it: XML allows you to store data regardless of how it will be displayed.

XML is a common standard: XML was developed by the World Wide Web Consortium (W3C) and is available as an open standard.

XML is built on a nested node structure. Each node will have an opening tag and a closing tag as follows:

In which:

content is the content of this tag.

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:

What is Gson?

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();

What is JAXB?

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:

@XmlRootElement: This annotation specifies what the outermost tag of the XML file is and therefore it is declared on top of a class.

@XmlElementWrapper: This annotation creates a wrapper XML element around collections.

@XmlElement: This annotation used to declare an attribute of the object is a tag of the XML file.

@XmlAttribute: This annotation also used to declare an attribute of the object is a tag of the XML file.

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(); How to convert XML to JSON?

We implement the example of XML – JSON conversion on the platform:

Open JDK 8 for Ubuntu 18.04 x64.

Eclipse IDE 2023-03 (4.11.0) x64 Java Development for Ubuntu.

Gson 2.8.5.

Create a new Java Project.

Create a new Java Project. Set Project name is XmlToJsonExample.

Set Project name.

Create folder data/input containing two file chúng tôi and sample.json.

Create folder data/input.

Let’s first define our XML with department, role and person properties.

Object Relationships.

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" } ] } ] }

Define corresponding object classes in the package model.

Define object classes.

Role.java:

@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; } }

Person.java:

@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; } }

Department.java:

@XmlRootElement(name = "department") public class Department { public Department() { super(); } super(); this.roles = roles; this.persons = persons; } @XmlElementWrapper(name = "roles") @XmlElement(name = "role") return roles; } this.roles = roles; } @XmlElementWrapper(name = "persons") @XmlElement(name = "person") return 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; } }

Add and Set up library Gson 2.8.5 into Java Build Path.

Add library Gson 2.8.5 into Java Build Path.

Convert XML message to Java objects using JAXB

Firstly, we define performing classed in package service.

Define performing classes.

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();

Then we go to next step.

Convert Java objects to JSON message using Gson

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.

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.

Convert JSON message to Java objects using Gson

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.

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(); jsonService.getDataFromJsonFile(filePathIn, roles, persons); How to Convert Json to XML Java?

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.

Convert Java objects to XML message using JAXB

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.

Conclusion

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.

You're reading Convert Json To Xml Java Using Gson And Jaxb With Example

Update the detailed information about Convert Json To Xml Java Using Gson And Jaxb With Example on the Benhvienthammyvienaau.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!