Giter Club home page Giter Club logo

jsontojava's Introduction

JsonToJava

A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generate 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 Tested on java version 1.6

Tips

Specify all values for json fields with non-null values. By doing so, the generator will try to re-use classes it already generated in other structures as long as the class can be parsed back from json into the generated class.

Limitations

Uses Jackson and generates @JsonProperty annotations for json fields Can't discover and create abstract types Can't collate unspecified fields across different structures into the same class when missing information Doesn't support byte, short and char types yet Running the sample

$ ./sample-run.sh

jsontojava's People

Contributors

astav avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsontojava's Issues

String replaceAll has a gotcha in JavaTemplate.writeOutJavaFile

Somewhere around line 36 of the class JavaTemplate, method writeOutJavaFile, there is the following line:
String packageDirectory = packageName.replaceAll(".", File.separator);

On most MS Systems, file separator is set to '', so this causes an error if you have a dot/period (.) in your packageName (and most often, you will).
The String replaceAll is a nice and powerful method, but it is overkill here, especially since (as Chris Smith points out at http://www.velocityreviews.com/forums/t127000-replace-period-using-string-replaceall.html) "the second parameter isn't just a String either; it's a pseudo-regexp where most special characters don't work, but subexpression references do. That means, essentially, that you have to be sure to properly escape BOTH parameters to this method (and in consequence, the method is practically useless unless both parameter values are known when the code is written)."

For example, try this bit of code:
String packageName = "com.example3";
String result = packageName.replaceAll(".", File.separator);
System.out.println("result= " + result);
You'll get the following error:
Replacing the period in com.example3 with ''
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at java.util.regex.Matcher.appendReplacement(Matcher.java:762)
at java.util.regex.Matcher.replaceAll(Matcher.java:906)
at java.lang.String.replaceAll(String.java:2162)
at MyClass.main(MyClass.java:53)

You can fix it by replacing the File.separator, which screws up the Java/regex syntax because of the backslash(), with four backslashes:

      String result = packageName.replaceAll("\\.", "\\\\");

But then the code would break in Linux. OTOH, if you just do a simpler "replace" of "." instead:
String result = packageName.replace(".", File.separator);

Then it works fine. BTW, it works no matter how many dots you have in your packageName (I used to be under the same misconception; that if Java had a replaceAll, then the regular "replace", must only replace the first substring; this is not the case). My output:

  result= com\my\example3

NullPointerException

I tested this (also with Java 1.6) and got following error

jirkay@ittest> ./sample-run.sh                                                                                                 ~/JsonToJava
rm: cannot remove ‘out/test/*’: No such file or directory
rmdir: failed to remove ‘out/test’: No such file or directory
rmdir: failed to remove ‘out’: No such file or directory
JsonToJava v0.1

Package name is 'test'
Output directory is 'out'
Using regex file 'regex-sample.json'
Not importing existing classes.
Generating classes....
  Using Long for json field 'testRegexInMs'
Writing file 'out/test/RealMapEntry.java' ...done.
Exception in thread "main" java.lang.NullPointerException
        at com.astav.jsontojava.classmanager.GeneratedClassManager.compileAndLoadClass(GeneratedClassManager.java:49)
        at com.astav.jsontojava.Generator.generateClasses(Generator.java:93)
        at com.astav.jsontojava.Generator.generateClasses(Generator.java:88)
        at com.astav.jsontojava.JsonToJava.main(JsonToJava.java:52)

Error 415 when doing post json

I have a REST application that responds xml, but I want to change it to respond json. I'm managing to do GET, but I can not do POST, PUT and DELETE. What should I include?
Follow the code below:

package pojo;

import java.io.Serializable;

import javax.management.ObjectName;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Curso implements Serializable {

private int codigo;
private String nome;

// private ArrayList<Aluno> alunos = new ArrayList<Aluno>();

public Curso(int codigo, String nome) {
    super();
    if ((codigo > 0) && (codigo < 100) && (!nome.isEmpty()))
    {
        this.codigo = codigo;
        this.nome = nome;
    }
    else
    {
        System.out.println("Digite um código válido");
    }

}

public Curso() {

}

public int getCodigo() {
    return codigo;
}

public void setCodigo(int codigo) {
    this.codigo = codigo;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

}


package resources;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

import pojo.Curso;
import client.EscolaService;

@path("curso")
@consumes("application/json")
@produces(MediaType.APPLICATION_JSON)
public class CursoResource {

private EscolaService escolaService;

public CursoResource() {
    this.escolaService = new EscolaService();
}

@GET
@Path("{codigo}")
public Response buscarCurso(@PathParam("codigo") String codigo) {
    Curso curso = escolaService.buscarCurso(new Integer(codigo).intValue());
    if (curso == null) {
        return Response.status(HttpServletResponse.SC_NOT_FOUND).build();
    }

    System.out.println(new Gson().toJson(curso));

    Response resposta = Response.ok(new Gson().toJson(curso)).build();
    return resposta;// coloquei porque estava dando erro
}

@POST
@Consumes("application/json")
public Response cadastrarCurso(Curso curso) {
    if ((curso.getCodigo() > 0) && (curso.getCodigo() < 100))
    {
        curso = escolaService.cadastrarCurso(curso);
        try {
            return Response.created(new URI("" + curso.getCodigo())).build();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    Response resposta = Response.ok(new Gson().toJson(curso)).build();
    return resposta.noContent().build();
}

@PUT
public Response alterarCurso(Curso curso) {
    curso = escolaService.alterarCurso(curso);
    try {
        return Response.created(new URI("" + curso.getCodigo())).build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

@DELETE
@Path("{codigo}")
public Response removerCurso(@PathParam("codigo") String codigo) {
    boolean excluir = escolaService.removerCurso(new Integer(codigo)
            .intValue());
    if (excluir == false) {
        return Response.status(HttpServletResponse.SC_NOT_FOUND).build();
    }
    Response resposta = Response.ok().build();
    return resposta;
}

@GET
@Produces("text/plain")
public String listarCursos() {
    List<Integer> codigos = new ArrayList<Integer>();
    List<String> nomes = new ArrayList<String>();
    for (Iterator<Curso> it = escolaService.listarCursos().iterator(); it
            .hasNext();) {
        Curso curso = (Curso) it.next();
        codigos.add(curso.getCodigo());
        nomes.add(curso.getNome());

    }
    String separador = System.getProperty("line.separator");
    return ("Cursos" +separador+ separador+ "Codigos: " + codigos.toString() +separador+ "Nomes: " + nomes.toString());
}

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.