Home >Java >javaTutorial >How Can I Generate Java Classes from JSON Data Using the jsonschema2pojo Maven Plugin?
As a Java developer, you may encounter situations where you need to generate Java source files from JSON data. This can be a valuable technique for creating data transfer objects (DTOs) or POJOs (Plain Old Java Objects) that mirror JSON structures.
Here's how to accomplish this using the jsonschema2pojo Maven plugin:
<plugin> <groupId>org.jsonschema2pojo</groupId> <artifactId>jsonschema2pojo-maven-plugin</artifactId> <version>1.0.2</version> <configuration> <sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory> <targetPackage>com.myproject.jsonschemas</targetPackage> <sourceType>json</sourceType> </configuration> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin>
Consider the following JSON data:
{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York" } }
Upon running the Maven plugin, the following Java classes will be generated:
class Address { JSONObject mInternalJSONObject; Address (JSONObject json){ mInternalJSONObject = json; } String getStreetAddress () { return mInternalJSONObject.getString("streetAddress"); } String getCity (){ return mInternalJSONObject.getString("city"); } } class Person { JSONObject mInternalJSONObject; Person (JSONObject json){ mInternalJSONObject = json; } String getFirstName () { return mInternalJSONObject.getString("firstName"); } String getLastName (){ return mInternalJSONObject.getString("lastName"); } Address getAddress (){ return Address(mInternalJSONObject.getString("address")); } }
These generated classes provide easy access to the data in the JSON structure, enabling you to work with the data in a convenient and object-oriented manner.
The above is the detailed content of How Can I Generate Java Classes from JSON Data Using the jsonschema2pojo Maven Plugin?. For more information, please follow other related articles on the PHP Chinese website!