我有json数据的蛇案例表示'{“first_name”:“Michael”,“last_name”:“Jordan”,“address_loc”:{“city_name”:“Mumbai”,“street”: “galino1”}}“。我想通过基于jersey + moxy的post方法资源以pojo表示形式使用这些数据。请建议。请注意,json的正常camel case表示正在使用给定的以下代码片段,但我需要使用snake case。
@XmlRootElement
public class Person {
private String firstName;
private String lastName;
private AddressLoc addressLoc = new AddressLoc();
public Person(){};
public Address getAddressLoc() {
return addressLoc ;
}
public void setAddressLoc(Address address) {
this.addressLoc = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
子/嵌套类
public class AddressLoc {
private String cityName;
private String street;
public AddressLoc(){};
public String getCityName() {
return cityName;
}
public void setCityName(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
资源类
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.nabisoft.tutorials.jerseymoxy.model.Person;
@Path("/person")
public class PersonResource {
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.TEXT_PLAIN})
@Path("/post")
public String postPerson(Person pers) throws Exception{
System.out.println("First Name = "+pers.getFirstName());
System.out.println("Last Name = "+pers.getLastName());
System.out.println("Last Name = "+pers.getAddress().getCity());
System.out.println("Last Name = "+pers.getAddress().getStreet());
return "ok";
}
}
客户端代码
<script src="<%=request.getContextPath() %>/js/jquery-1.11.2.min.js"></script>
<script>
var ctxPath = "<%=request.getContextPath() %>";
$(function(){
$("#postPerson, #postMessage").on("click", function(){
$.ajax({
url: $(this).attr("id") === "postMessage" ? ctxPath+"/service/message/post" : ctxPath+"/service/personwa/post",
type: "POST",
data: '{"first_name":"Michael", "last_name":"Jordan", "address_loc":{"city_name":"Mumbai", "street":"galino1"}}',
contentType: "application/json",
cache: false,
dataType: "json"
});
});
});
</script>
除了上面列出的代码库之外,我还有“ApplicationConfig.java”和“JsonMoxyConfigurationContextResolver.java”,其中没有任何花哨的实现。感谢。
答案 0 :(得分:2)
您想添加 javax.xml.bind.annotation.XmlElement 注释并提供另一个(蛇案例)名称。
@XmlRootElement
public class Person {
@XmlElement(name="first_name")
private String firstName;