astav / jsontojava Goto Github PK
View Code? Open in Web Editor NEWJson to Java source code generator for Jackson (see the wiki https://github.com/astav/JsonToJava/wiki/JsonToJava)
Home Page: https://github.com/astav/JsonToJava/wiki/JsonToJava
Json to Java source code generator for Jackson (see the wiki https://github.com/astav/JsonToJava/wiki/JsonToJava)
Home Page: https://github.com/astav/JsonToJava/wiki/JsonToJava
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());
}
}
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)
Hi,
would be hawt if your tool could be run from maven as build plugin
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.