Generate Java class from JSON?

JavaJson

Java Problem Overview


In a Java Maven project, how do you generate java source files from JSON? For example we have

{
  "firstName": "John",  
  "lastName": "Smith",  
  "address": {  
	"streetAddress": "21 2nd Street",  
	 "city": "New York"
  }
}

When we run mvn generate-sources we want it to generate something like this:

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"));
	}
}

As a Java developer, what lines of XML do I need to write in my pom.xml in order to make this happen?

Java Solutions


Solution 1 - Java

Try http://www.jsonschema2pojo.org

Or the jsonschema2pojo plug-in for Maven:

<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>

The <sourceType>json</sourceType> covers the case where the sources are json (like the OP). If you have actual json schemas, remove this line.

Updated in 2014: Two things have happened since Dec '09 when this question was asked:

  • The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules

  • I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

Hope this helps!

Solution 2 - Java

If you're using Jackson (the most popular library there), try

https://github.com/astav/JsonToJava

Its open source (last updated on Jun 7, 2013 as of year 2021) and anyone should be able to contribute.

Summary

A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generates the necessary java data structures.

It encourages teams to think in Json first, before writing actual code.

Features

  • Can generate classes for an arbitrarily complex hierarchy (recursively)
  • Can read your existing Java classes and if it can deserialize into those structures, will do so
  • Will prompt for user input when ambiguous cases exist

Solution 3 - Java

Here's an online tool that will take JSON, including nested objects or nested arrays of objects and generate a Java source with Jackson annotations.

Solution 4 - Java

Answering this old question with recent project ;-).

At the moment the best solution is probably JsonSchema2Pojo :

It does the job from the seldom used Json Schema but also with plain Json. It provides Ant and Maven plugin and an online test application can give you an idea of the tool. I put a Json Tweet and generated all the containing class (Tweet, User, Location, etc..).

We'll use it on Agorava project to generate Social Media mapping and follow the contant evolution in their API.

Solution 5 - Java

Thanks all who attempted to help.
For me this script was helpful. It process only flat JSON and don't take care of types, but automate some routine

  String str = 
        "{"
            + "'title': 'Computing and Information systems',"
            + "'id' : 1,"
            + "'children' : 'true',"
            + "'groups' : [{"
                + "'title' : 'Level one CIS',"
                + "'id' : 2,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Intro To Computing and Internet',"
                    + "'id' : 3,"
                    + "'children': 'false',"
                    + "'groups':[]"
                + "}]" 
            + "}]"
        + "}";
    


    JSONObject json = new JSONObject(str);
    Iterator<String> iterator =  json.keys();
    
    System.out.println("Fields:");
    while (iterator.hasNext() ){
       System.out.println(String.format("public String %s;", iterator.next()));
    }
    
    System.out.println("public void Parse (String str){");
    System.out.println("JSONObject json = new JSONObject(str);");
    
    iterator  = json.keys();
    while (iterator.hasNext() ){
       String key = iterator.next();
       System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));

    System.out.println("}");

Solution 6 - Java

I'm aware this is an old question, but I stumbled across it while trying to find an answer myself.

The answer that mentions the online json-pojo generator (jsongen) is good, but I needed something I could run on the command line and tweak more.

So I wrote a very hacky ruby script to take a sample JSON file and generate POJOs from it. It has a number of limitations (for example, it doesn't deal with fields that match java reserved keywords) but it does enough for many cases.

The code generated, by default, annotates for use with Jackson, but this can be turned off with a switch.

You can find the code on github: https://github.com/wotifgroup/json2pojo

Solution 7 - Java

I created a github project Json2Java that does this. https://github.com/inder123/json2java

Json2Java provides customizations such as renaming fields, and creating inheritance hierarchies.

I have used the tool to create some relatively complex APIs:

Gracenote's TMS API: https://github.com/inder123/gracenote-java-api

Google Maps Geocoding API: https://github.com/inder123/geocoding

Solution 8 - Java

I had the same problem so i decided to start writing a small tool to help me with this. Im gonna share andopen source it.

https://github.com/BrunoAlexandreMendesMartins/CleverModels

It supports, JAVA, C# & Objective-c from JSON .

Feel free to contribute!

Solution 9 - Java

I know there are many answers but of all these I found this one most useful for me. This link below gives you all the POJO classes in a separate file rather than one huge class that some of the mentioned websites do:

https://json2csharp.com/json-to-pojo

It has other converters too. Also, it works online without a limitation in size. My JSON is huge and it worked nicely.

Solution 10 - Java

As far as I know there is no such tool. Yet.

The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.

However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.

So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

Solution 11 - Java

You could also try GSON library. Its quite powerful it can create JSON from collections, custom objects and works also vice versa. Its released under Apache Licence 2.0 so you can use it also commercially.

http://code.google.com/p/google-gson/

Solution 12 - Java

Try my solution

http://htmlpreview.github.io/?https://raw.githubusercontent.com/foobnix/android-universal-utils/master/json/generator.html

{
    "auctionHouse": "sample string 1",
    "bidDate": "2014-05-30T08:20:38.5426521-04:00 ",
    "bidPrice": 3,
    "bidPrice1": 3.1,
    "isYear":true
}

Result Java Class

private String  auctionHouse;
private Date  bidDate;
private int  bidPrice;
private double  bidPrice1;
private boolean  isYear;

JSONObject get

auctionHouse = obj.getString("auctionHouse");
bidDate = obj.opt("bidDate");
bidPrice = obj.getInt("bidPrice");
bidPrice1 = obj.getDouble("bidPrice1");
isYear = obj.getBoolean("isYear");

JSONObject put

obj.put("auctionHouse",auctionHouse);
obj.put("bidDate",bidDate);
obj.put("bidPrice",bidPrice);
obj.put("bidPrice1",bidPrice1);
obj.put("isYear",isYear);

Solution 13 - Java

To add to @japher's post. If you are not particularly tied to JSON, Protocol Buffers is worth checking out.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDenis PalnitskyView Question on Stackoverflow
Solution 1 - JavajoelittlejohnView Answer on Stackoverflow
Solution 2 - JavaAstavView Answer on Stackoverflow
Solution 3 - JavaTim BoudreauView Answer on Stackoverflow
Solution 4 - JavaAntoine Sabot-DurandView Answer on Stackoverflow
Solution 5 - JavaDenis PalnitskyView Answer on Stackoverflow
Solution 6 - JavaChris RView Answer on Stackoverflow
Solution 7 - JavainderView Answer on Stackoverflow
Solution 8 - JavaehanocView Answer on Stackoverflow
Solution 9 - JavaxbmonoView Answer on Stackoverflow
Solution 10 - JavaStaxManView Answer on Stackoverflow
Solution 11 - JavaMB.OneView Answer on Stackoverflow
Solution 12 - JavaFoobnixView Answer on Stackoverflow
Solution 13 - JavadgorissenView Answer on Stackoverflow