Advertisement
Advertisement


Generate Java class from JSON?


Question

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?

2020/06/08
1
220
6/8/2020 12:43:38 AM


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 2020) 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
2020/07/22

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.

2015/02/07

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.


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("}");
2009/12/25

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

2011/12/21

Source: https://stackoverflow.com/questions/1957406
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]