Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow JSON to be passed as a String to SchemaMapper (add sourceType support in #221) #255

Closed
diegosoaresub opened this issue Oct 3, 2014 · 14 comments

Comments

@diegosoaresub
Copy link

Hello,

In http://www.jsonschema2pojo.org/ I could convert JSON to POJO, but using the API this not work, only Json Schema to POJO. Is possible do this with the API?

In this case below, I didn't get exception but It doesn't generate the java file.

JCodeModel codeModel = new JCodeModel();
SchemaMapper schemaMapper = new SchemaMapper();
schemaMapper.generate(codeModel, className, packageName, "{"titulo": "JSON"}");
codeModel.build(new File("output"));

@diegosoaresub
Copy link
Author

How I can configure the convertion like the website?

@joelittlejohn
Copy link
Owner

Could you give this a try:

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

final JCodeModel codeModel = new JCodeModel();
final RuleFactory ruleFactory = new RuleFactory(config, new Jackson2Annotator(), new SchemaStore());
final SchemaMapper schemaMapper = new SchemaMapper(ruleFactory, new SchemaGenerator());

schemaMapper.generate(codeModel, className, packageName, "{\"titulo\": \"JSON\"}");

codeModel.build(new File("output"));

@joelittlejohn
Copy link
Owner

Ah, actually it looks like the change made in #221 to allow source documents to be generated from strings doesn't use the config correctly, so it doesn't support sourceType=JSON. You'll need to use a URL to pass the JSON content.

If you can't use a URL, you could also take a look inside SchemaMapper and copy some of the logic in there. It's all about calling the rulefactory with the right JsonNode.

@joelittlejohn joelittlejohn changed the title How to convert json to pojo? Allow JSON to be passed as a String to SchemaMapper (add sourceType support in #221) Oct 3, 2014
@diegosoaresub
Copy link
Author

Hello, Using the URL the convertion works, but with string not.

@MadhuMeka
Copy link

Hi,

I am trying to use your utility in my project and tried in the exact way mentioned in the code snippet that you have provided. But when I do codeModel.build(new File("output")); I m getting non-existent directory exception. Then I tried to give an existing directory in it. But I don't see the generated file. Can you please help me with this issue?
My code:

public void getPOJO(String JSONsource){

    JCodeModel codeModel = new JCodeModel();
    URL source;
    try {
        source = new URL("file:///C:/E_MailServiceProject/EmailServiceProject/WebContent/sample.json");


    new SchemaMapper().generate(codeModel, "MailMergeBean", "com.emailservice.controller", source);


    codeModel.build(new File("output"));
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        }

Thanks,
Madhu

@joelittlejohn
Copy link
Owner

What is the content of sample.json? Is it plain JSON or JSON schema? If it's plain json, you need to set sourceType JSON, like this:

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

final JCodeModel codeModel = new JCodeModel();
final RuleFactory ruleFactory = new RuleFactory(config, new Jackson2Annotator(), new SchemaStore());
final SchemaMapper schemaMapper = new SchemaMapper(ruleFactory, new SchemaGenerator());

@MadhuMeka
Copy link

I don't see any errors or exceptions but for some reason it does not create my class.

Here is my code after adding your suggestion.

public void getPOJO(String JSONsource){

    final GenerationConfig config = new DefaultGenerationConfig() {
        @Override
        public SourceType getSourceType() {
            return SourceType.JSON;
        }
    };
    URL source;
    try {
        source = new URL("file:///C:/E_MailServiceProject/EmailServiceProject/WebContent/sample.json");
        java.io.BufferedInputStream jsonContent = (BufferedInputStream) source.getContent();

        byte[] contents = new byte[1024];
        int bytesRead = 0;
        String strFileContents = "";
        while ((bytesRead = jsonContent.read(contents)) != -1) {
          strFileContents = new String(contents, 0, bytesRead);
          System.out.print(strFileContents);
        }
        jsonContent.close();

    final JCodeModel codeModel = new JCodeModel();
    final RuleFactory ruleFactory = new RuleFactory(config, new Jackson2Annotator(), new SchemaStore());
    final SchemaMapper schemaMapper = new SchemaMapper(ruleFactory, new SchemaGenerator());
    schemaMapper.generate(codeModel, "MailMergeBean", "net.emailservice.new", strFileContents);

    codeModel.build(new File("."));
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Thanks,
Madhu

@joelittlejohn
Copy link
Owner

The reason this bug is currently still open is that #221 added support for passing strings to the SchemaMapper as content, but it doesn't currently support JSON (only JSON Schema). If you want to generate JSON, you need to pass the URL to the SchemaMapper instead:

schemaMapper.generate(codeModel, "MailMergeBean", "net.emailservice.new", source);

@sanalsan
Copy link

Hello,
Is there any hope for this bug ?

@joelittlejohn
Copy link
Owner

@sanalsan happy to accept a pull request for this if you are interested in fixing it.

@sanalsan
Copy link

Hello Joe,

can you please tell me the error in it ?

package com.schoolspeak.modelgenerator;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;

import com.sun.codemodel.JCodeModel;

import org.jsonschema2pojo.DefaultGenerationConfig;
import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Jackson2Annotator;
import org.jsonschema2pojo.SchemaGenerator;
import org.jsonschema2pojo.SchemaMapper;
import org.jsonschema2pojo.SchemaStore;
import org.jsonschema2pojo.SourceType;
import org.jsonschema2pojo.rules.RuleFactory;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    generateClassFromJsonString();
}
private File getFile(){
    File mPath = new

File(Environment.getExternalStorageDirectory(), "Model");
if (!mPath.exists()) {
try {
mPath.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
return mPath;
}
private void generateClassFromJsonString(){
JCodeModel codeModel = new JCodeModel();
String jsonString="{ "accounting" : [ \n" +
" { "firstName" :
"John", \n" +
" "lastName" : "Doe",\n" +
" "age" : 23 },\n" +
"\n" +
" { "firstName" :
"Mary", \n" +
" "lastName" :
"Smith",\n" +
" "age" : 32 }\n" +
" ],
\n" +
" "sales" : [ \n" +
" { "firstName" :
"Sally", \n" +
" "lastName" :
"Green",\n" +
" "age" : 27 },\n" +
"\n" +
" { "firstName" :
"Jim", \n" +
" "lastName" :
"Galley",\n" +
" "age" : 41 }\n" +
" ] \n" +
" } ";

    final GenerationConfig config = new DefaultGenerationConfig() {
        @Override
        public SourceType getSourceType() {
            return SourceType.JSON;
        }
    };
    SchemaMapper mapper = new SchemaMapper(new RuleFactory(config,

new Jackson2Annotator(),
new SchemaStore()), new SchemaGenerator());
try {
mapper.generate(codeModel,"sample", "com.sample.model.",
jsonString);
} catch (IOException e) {
e.printStackTrace();
}

    try {
        codeModel.build(getFile());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

On Fri, Nov 27, 2015 at 4:15 PM, Joe Littlejohn notifications@github.com
wrote:

@sanalsan https://github.com/sanalsan happy to accept a pull request
for this if you are interested in fixing it.


Reply to this email directly or view it on GitHub
#255 (comment)
.

Thanks & Regards,
Sanal K | Software Developer
Suyati Technologies | http://www.suyati.com
skalathingal@suyati.com hcherian@socxo.com| P: 9895442668
[image: http://www.suyati.com/images/signature_new/white.jpg][image:
LinkedIn]
http://t.strk03.email/e1t/c/5/f18dQhb0S7lC8dDMPbW2n0x6l2B9nMJN7t5XZsQZbjKW7dSn5C1px3lzW7fsH1M56dBH6f80fbP402?t=https%3A%2F%2Fin.linkedin.com%2Fpub%2Fsanal-k%2F6a%2F782%2F216&si=5828738894266368&pi=24522bb9-f3f7-467f-c171-7f46f9199641[image:
http://www.suyati.com/images/signature_new/white.jpg][image: Facebook]
http://t.strk03.email/e1t/c/5/f18dQhb0S7lC8dDMPbW2n0x6l2B9nMJN7t5XZsQZbjKW7dSn5C1px3lzW7fsH1M56dBH6f80fbP402?t=https%3A%2F%2Fwww.facebook.com%2Fsanal.saw&si=5828738894266368&pi=24522bb9-f3f7-467f-c171-7f46f9199641[image:
http://www.suyati.com/images/signature_new/white.jpg][image: Twitter]
http://t.strk03.email/e1t/c/5/f18dQhb0S7lC8dDMPbW2n0x6l2B9nMJN7t5XZsQZbjKW7dSn5C1px3lzW7fsH1M56dBH6f80fbP402?t=https%3A%2F%2Ftwitter.com%2Fsanal_san&si=5828738894266368&pi=24522bb9-f3f7-467f-c171-7f46f9199641

@joelittlejohn
Copy link
Owner

The error is exactly as described already:

the change made in #221 to allow source documents to be generated from strings doesn't use the config correctly, so it doesn't support sourceType=JSON. You'll need to use a URL to pass the JSON content.

@sanalsan
Copy link

sanalsan commented Dec 8, 2015

@joelittlejohn
Copy link
Owner

Closed by #475

Repository owner deleted a comment from JohnLuCN Apr 2, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants