简体   繁体   中英

Get json object data on jax-rs

I have this put method on my web service ,this method consumes a json object ,but how i can get this data inside my method if the method receives a json object with name,surname,afiliation and country fields?

@PUT
@Path("/Updatemember/{nom}/{ape}/{afi}/{nac}")
@Consumes({"application/json"})
@Produces(MediaType.TEXT_PLAIN)
public String Updatemember(@PathParam("nom")String nombre, @PathParam("ape")String apellido, 
                            @PathParam("afi")String afiliacion, @PathParam("nac")String nacionalidad) throws SQLException
{
    Miembro.update(nombre, apellido, afiliacion, nacionalidad);
    return "Data has been updated";
}

edit: Now the method is

@PUT
@Path("/Updatemember/")
@Consumes({"application/json"})
@Produces(MediaType.TEXT_PLAIN)
public String Updatemember(Miembro miembro) throws SQLException
{
    miembro.update();
    return "Se han actualizado los datos del miembro";
}

and the class member(miembro in spanish) has this method ,which works fine.

public void update() throws SQLException
{
    Connection conexion = Conexion.GetConnection();
    String sql = "UPDATE miembros SET afiliacion='"+getAfiliacion()+"', nacionalidad='"+getNacionalidad()+"' WHERE nombre='"+getNombre()+"' AND apellidos='"+getApellidos()+"'";
    PreparedStatement pre = (PreparedStatement) conexion.prepareStatement(sql);
    pre.execute();
}

Updatemember gives me a Nullpoiter exception,the miembro object is not create but i don't know why.

Your method signature is saying that you take in four path parameters (not json - you can have queryParams as json though).

If you create a class called Member with those parameters as members of the class:

@XmlRootElement
 public class Member {
      // public constructor 
      // getters and setters for your fields
 }

Then let the class be a parameter to your method and change path to @Path("/UpdateMember/{id}").

If you make sure to have either jackson or moxy on the classpath, your Member parameter should be a valid object-instance of class Member.

Read up on the jersey docs here: https://jersey.java.net/documentation/latest/media.html#json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM