Problem:
In a Java Maven project, how can you generate Java source files from a JSON schema? For instance, given the following JSON:
{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York" } }
You want to generate Java classes like:
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")); } }
Solution:
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>
Set sourceType to json if your source is JSON directly. For JSON schemas, remove this line.
Additional Tips:
The above is the detailed content of How can I generate Java classes from a JSON schema in a Maven project?. For more information, please follow other related articles on the PHP Chinese website!