9

I was following the link Generate Java class from JSON? to create the POJO classes from json string (and not from schema). I am using jsonschema2pojo jar of version 0.4.10 but could not able to generate the POJO class. My code is as below,

public class App 
{
    public static void main( String[] args )
    {
        JCodeModel codeModel = new JCodeModel();        
        try {
            URL source = new URL("file:///C://Users//...//accession.json");
            new SchemaMapper().generate(codeModel, "Accession", "com.test", source);
            File dir = new File("D://test");
            if(dir.exists()){
                System.out.println("dir available");
                codeModel.build(dir);
            }else{
                System.out.println("dir not available");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
}

So accession.json has json string which need to be converted into POJO. Can anybody please help me here.

Community
  • 1
  • 1

4 Answers4

8

I had a similar experience using the command-line tool. In my case, it was the result of not correctly specifying the source type (JSONSCHEMA or JSON; default: JSONSCHEMA).

I think your problem is similar: You're using the default (no-args) constructor for SchemaMapper. The following steps should solve the problem:

  1. Subclass org.jsonschema2pojo.DefaultGenerationConfig, overriding getSourceType() to return SourceType.JSON
  2. Use an instance of that subclass for the SchemaMapper(RuleFactory ruleFactory, SchemaGenerator schemaGenerator) constructor (instead of the no-args constructor).
Zephyr
  • 226
  • 1
  • 5
6

Once I faced the same problem and then I resolved this. In your code you are using Default Configuration which takes Source Type Jason Schema. But when You are giving input Jason you have to set this return type in this way : SourceType.JSON in your Configuration.

class App
{   
    public static void main( String[] args )
        {
            JCodeModel codeModel = new JCodeModel();        
            try {
                URL source= new URL("file:///D:/temp.json");
                GenerationConfig config = new DefaultGenerationConfig() {
                    @Override
                    public boolean isGenerateBuilders() {
                    return true;
                    }
                    public SourceType getSourceType(){
                        return SourceType.JSON;
                    }
                    };
                    SchemaMapper mapper =new SchemaMapper(new RuleFactory(config, new GsonAnnotator(), new SchemaStore()), new SchemaGenerator());
                    mapper.generate(codeModel, "Accession", "com.test", source);
                File dir = new File("D://");
                if(dir.exists()){
                    System.out.println("dir available");
                    codeModel.build(dir);
                }else{
                    System.out.println("dir not available");
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }       
        }
}

I hope It will help you.. Good Luck !!

Kapil
  • 71
  • 2
  • 5
2

I also struggled a bit with this. I did the following in the end:

Created my own GenerationConfig, overriding getSourceType:

static class MyConfig extends DefaultGenerationConfig {
    @Override
    public SourceType getSourceType() {
        return SourceType.JSON;
    }
}

I then initialised the build process as follows:

private void parseFileExample() {               
    URL source = new URL("file:/tmp/input/blah.json");
    JCodeModel codeModel = new JCodeModel();
    MyConfig generationConfig = new MyConfig();
    RuleFactory ruleFactory = new RuleFactory(generationConfig, new GsonAnnotator(), new SchemaStore());
    SchemaGenerator generator = new SchemaGenerator();

    SchemaMapper mapper = new SchemaMapper(ruleFactory, generator);
    mapper.generate(codeModel, "MyClass", "com.drakedroid", source);

    codeModel.build(new File("/tmp/output/"));
}

The trick here was, to use an URL. The mapper.generate didn't work when I passed in just a string.

Pieter
  • 2,143
  • 3
  • 14
  • 13
0

Thanks @Kapil, your answer helped me. This program allows us to generate POJO classes according to predefined JSON. We can also use it at runtime, where JSON response is not known, write the JSON response to the file and read it accordingly using the following code.

public class JSONExample {

  public static void main(String... args)  {

    JCodeModel codeModel = new JCodeModel();

    try
    {
        // In sample.json I have already pasted a JSON
        File file=new File("//root//AndroidStudioProjects//MyApplication//sample.json");
        URL source = file.toURI().toURL();

        GenerationConfig config = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() 
            {
                return true;
            }
            public SourceType getSourceType()
            {
                return SourceType.JSON;
            }
        };

        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(), new SchemaStore()), new SchemaGenerator());
        try {
            // The ClassName is the main class that will contain references to other generated class files
            // com.example is the package name 
            mapper.generate(codeModel, "ClassName", "com.example", source);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Directory where classes will be genetrated
            File file1=new File("//root//AndroidStudioProjects//MyApplication//");
            if (file1.exists())
            {
                System.out.println("dir available");
                codeModel.build(file1);
            }
            else
            {
                System.out.println("dir not available");
            }

            System.out.println(""+file1+" Exists "+file1.exists());


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    catch(Exception e)
    {
        e.printStackTrace();
    }
 }
}
ashishdhiman2007
  • 807
  • 2
  • 13
  • 28