gpt4 book ai didi

java - 基于 Jersey Moxy 的休息服务不消耗嵌套 json post 请求负载

转载 作者:行者123 更新时间:2023-11-30 03:19:06 24 4
gpt4 key购买 nike

我有 json 数据的蛇形表示形式'{"first_name":"Michael", "last_name":"Jordan", "address_loc":{"city_name":"Mumbai", "street": “galino1”}}'。我想通过基于 jersey + moxy 的 post 方法资源以 pojo 表示的形式使用这些数据。请建议。另请注意,正常的 json 驼峰式表示形式可以使用给定的以下代码片段进行工作,但我需要使用蛇式命名法。

@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”,其中没有任何花哨的实现。谢谢。

最佳答案

您想要添加 javax.xml.bind.annotation.XmlElement 注释并提供另一个(蛇形大小写)名称。

@XmlRootElement
public class Person {

@XmlElement(name="first_name")
private String firstName;

关于java - 基于 Jersey Moxy 的休息服务不消耗嵌套 json post 请求负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31781938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com