245

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?

np_6
  • 514
  • 1
  • 6
  • 19
Denis Palnitsky
  • 18,267
  • 14
  • 46
  • 55

13 Answers13

298

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.

starball
  • 20,030
  • 7
  • 43
  • 238
joelittlejohn
  • 11,665
  • 2
  • 41
  • 54
  • 5
    Wouldn't someone who used your jsonschema2pojo tool have to write their own schema file then? The OP asked to start with a Json file, not a schema. Is there a companion tool to go from Json -> Schema? I assume that such a tool, if it existed, could only provide a guess. – Jeff Axelrod Mar 12 '12 at 17:05
  • 3
    As of version 0.3.3, you can use plain old JSON as input :) – joelittlejohn Sep 23 '12 at 21:08
  • 19
    ...and there's now an online generator too: http://jsonschema2pojo.org – joelittlejohn Oct 17 '12 at 19:54
  • Has Gson support too now :) – joelittlejohn Jul 14 '13 at 18:41
  • Doesn't work with local references, thus severely limiting the usefulness of this utility. – james.garriss May 22 '14 at 17:25
  • @james.garriss Local references work when using the tool via Maven, Gradle, Ant, CLI. They don't currently work at jsonschema2pojo.org (it's a quirk of the way the webapp creates an in-memory schema that isn't backed by any file). Easily fixed. – joelittlejohn May 22 '14 at 21:24
  • I tried the CLI with this JSON file (which is also a JSON Schema): http://json-schema.org/draft-04/schema#. StackOverFlow exception. Fixable, @joelittejohn? It would be a big help. Thanks. – james.garriss May 23 '14 at 11:15
  • @james.garriss The schema schema makes extensive use of union types, it's highly dynamic and not easily mappable to Java's type system. It's beyond what jsonschema2pojo could ever support. – joelittlejohn May 25 '14 at 22:21
  • This produces a popup that just says "Preview" and nothing else, or alternatively an empty jar. I'm guessing there is something going wrong, but there is no information given. Tried with a variety of input and settings. – Torque Jul 05 '14 at 14:03
  • @Torque This almost certainly means there's no types to generate. Try the mailing list or raise an issue on GitHub (showing your input) and I can explain how your schema is being interpreted. – joelittlejohn Jul 05 '14 at 18:21
  • 2
    Excellent tool. The supplied link contains an online tool where you can paste in sample JSON, click a button and get Java source. – mbmast Jan 12 '15 at 19:01
  • I tried the ant version but that didn't generate the java files, got empty jar. Now using http://pojo.sodhanalibrary.com/.. looks good to me. – whoami Mar 25 '15 at 07:04
  • @praki This probably means you're not using the right source type. If you want to use JSON and not JSON Schema, then you need to use sourceType JSON (see http://joelittlejohn.github.io/jsonschema2pojo/site/0.4.10/Jsonschema2PojoTask.html). – joelittlejohn Mar 25 '15 at 10:34
  • If you have node.js and npm installed, you can take a look at this package: https://github.com/rtoshiro/json2poxo – Hamiseixas Aug 31 '15 at 16:41
  • Why does Android Studio mark `@Generated("org.jsonschema2pojo")` as an error? I'd like to keep it in, but had to remove it to get rid of the error. Also, Android Studio doesn't like the generated `toString()` method – Someone Somewhere Jan 29 '16 at 12:39
  • Unfortunately Android doesn't include `@Generated` even though it's part of Java 6. You can get it from `org.glassfish:javax.annotation:10.0-b28`. – joelittlejohn Jan 29 '16 at 16:35
  • I'm interested to know more about the toString problem. Feel free to raise a bug. – joelittlejohn Jan 29 '16 at 16:35
  • @Darpan If you want to use larger input, feel free to use the Maven plugin, Gradle plugin, CLI, etc. We need to have a limit of some kind on the website. – joelittlejohn Mar 02 '16 at 14:09
  • Reports an error on complex JSON, while some others create classes. – CoolMind Sep 26 '16 at 06:32
  • @CoolMind What kind of JSON? Care to raise a bug? – joelittlejohn Sep 26 '16 at 11:42
  • @joelittlejohn, maybe I made something wrong. But I have a JSON with case-sensitive fields (almost equal), and it reports that that field already exists. Where can I raise a bug? – CoolMind Sep 26 '16 at 18:35
  • @joelittlejohn It's a great tool. But it doesn't make nested classes for nested objects as they were in the json. Maybe have an option to do that as well? will be a big help. – VipulKumar Nov 08 '16 at 06:45
  • @VipulKumar it definitely does support nested objects, whatever level of nesting you like. It doesn't support mixed type arrays, as binding this to Java is difficult. – joelittlejohn Nov 08 '16 at 14:41
  • @joelittlejohn It does support nested objects but it creates separate classes for all of them. I would like them to be inner classes. e.g. if I have object b inside object a, I would like class B to be an inner class of A. Hope you understand the problem. – VipulKumar Nov 09 '16 at 09:58
  • @joelittlejohn Yes, it is a great tool. But, it does not throw an error if it cannot create classes from JSON. In my case I copy pasted a json response from a web site as follows: {"result":[{"parent":"" ..... too long, but it was a well formatted JSON. it generated an empty file. After I removed {"result":[, it could generate. If it can thrown an error with possible location of the error in the string, it will be more useful. – user2995358 Jan 16 '17 at 02:42
  • @user2995358 If you pasted JSON then the most likely cause of receiving no generated output is that you used `Source type: JSON Schema` instead of `Source Type: JSON`. If you are still having trouble, please raise an issue on the github project. – joelittlejohn Jan 16 '17 at 14:30
  • @joelittlejohn I have used your jsonschema2pojo website a few times, and I was happy with the results. But since yesterday, I am unable to get any pojo classes from it. Every time I submit, I get a Not Found page. Is you website under maintenance?? – Dibyanshu Jaiswal Apr 11 '17 at 06:21
  • @dibyanshu-jaiswal It's working fine for me. What browser are you using and what is the URL in the browser when you see the 404? Are you accessing the site through a corporate proxy? Which step gives you a 404? I suggest using Chrome of Firefox and trying outside your corporate network. – joelittlejohn Apr 11 '17 at 10:03
  • @joelittlejohn - Instead of online converters, can we use any popular json to java library to convert json to Java code file, rather than a Java class file ? Would this be simple ? – MasterJoe Nov 20 '17 at 20:20
  • 1
    @testerjoe If you mean Java source code, then yes jsonschema2pojo does this, and it's available as a maven plugin, ant task, gradle extension, CLI tool, java library, etc... – joelittlejohn Nov 20 '17 at 23:42
  • This online generator is not working for past few days and its not showing error as well. – Nizamudeen Sherif Apr 24 '19 at 07:50
  • @NizamudeenSherif Works okay for me. It might be a problem with some kind of filtering on your internet connection. – joelittlejohn Apr 24 '19 at 08:36
  • Yes @joelittlejohn it works now, Thanks for update. – Nizamudeen Sherif Apr 24 '19 at 12:39
  • @joelittlejohn: Excellent tool. Thanks for that. I just have a little doubt here regarding its usage. Lets say I converted my json file to pojo using your tool. So now if I want to create an object of this class to use it in same code after class is build, how would I do that? I know my class name but wouldn't compiler say that this class not found as this class is not yet created at the time of compilation? I believe this class gets formed after we run the code and if in same code we create the object of this class, then wouldn't it be unable to compile? Just curious about this. – CodeHunter Jul 30 '19 at 19:23
  • @CodeHunter You use this tool before you compile. If you are still confused then probably best to ask a new StackOverflow question. – joelittlejohn Aug 12 '19 at 19:51
  • @joelittlejohn I figured it out how to use them both side by side. You can utilize java compiler classes for this purpose. All you need to do is provide the generated class as string content and then create object based on it. – CodeHunter Aug 12 '19 at 21:20
  • This has limitation in size. My schema is too large and the online tool doesn't generate anything – xbmono Jul 15 '21 at 05:08
  • 1
    @xbmono for very large schemas, it's best you use the tool locally (CLI/Maven/Gradle/Ant). – joelittlejohn Jul 15 '21 at 13:47
22

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
Asocia
  • 5,935
  • 2
  • 21
  • 46
Astav
  • 241
  • 2
  • 4
19

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.

Tim Boudreau
  • 1,741
  • 11
  • 13
  • 2
    This worked very well for me on the first go. I had deeply nested JSON and it worked fine, although I did have to trim redundant portions to get the overall size below 2k. Enabled me to write: MyClass c = new MyClass(); c = gson.fromJson(c.getHTML(someURLthatReturnsJSON), MyClass.class); and the resulting data flowed perfectly. I had to remove all those Jackson notations, but otherwise it worked fine for gson. Thank you. – noogrub Aug 01 '15 at 05:18
  • 1
    Thanks, it works. When I feeded a JSON with case-sensitive fields, this site returned a result, while www.jsonschema2pojo.org reported an error. – CoolMind Sep 26 '16 at 08:56
  • I was able to generate some java code today, but it stopped working then. The corresponding text area isn't there anymore... – ka3ak Mar 23 '21 at 13:54
7

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.

joelittlejohn
  • 11,665
  • 2
  • 41
  • 54
Antoine Sabot-Durand
  • 4,875
  • 17
  • 33
  • That's also my impression, but I didn't try the Maven plugin yet, however the online version is pretty slow and dies for anything other than the usual Person class... So for quick online conversion, @tim-boudreau's tool worked best for me. – Gregor Oct 02 '15 at 20:07
  • I tried JsonSchema2Pojo but hitting the Preview button pops up the blank preview. – AndroidDev Oct 23 '16 at 07:41
5

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("}");
Denis Palnitsky
  • 18,267
  • 14
  • 46
  • 55
5

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

Chris R
  • 199
  • 2
  • 2
3

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

inder
  • 1,774
  • 1
  • 15
  • 15
3

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.

xbmono
  • 2,084
  • 2
  • 30
  • 50
2

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!

ehanoc
  • 2,187
  • 18
  • 23
1

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/

MB.One
  • 110
  • 1
  • 2
1

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

StaxMan
  • 113,358
  • 34
  • 211
  • 239
1

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);
Foobnix
  • 719
  • 5
  • 7
-2

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

dgorissen
  • 6,207
  • 3
  • 43
  • 52
  • 2
    Protocol Buffers is not even close to an answer on how to create Java objects from JSON. At the very least you should have recommended a tool for creating Java Objects from Protocol Buffers. – james.garriss May 21 '14 at 20:05