gpt4 book ai didi

java - 复杂 Json 到嵌套 POJO spring MVC

转载 作者:行者123 更新时间:2023-12-02 11:38:07 31 4
gpt4 key购买 nike

我正在尝试使用 @RequestBody Instance instance 将以下 Json 导入 POJOS

{
"service_id": "service-id-here",
"plan_id": "plan-id-here",
"context": {
"platform": "cloudfoundry",
"some_field": "some-contextual-data"
},
"organization_guid": "org-guid-here",
"space_guid": "space-guid-here",
"parameters": {
"agent_name": 1,
"url": "foo",
"credential": "asdasd",
"ia_url": "asdasd"
}
}

下面是我的 POJO

实例

public class Instance {
@JsonProperty(value = "service_id")
String serviceId;
@JsonProperty(value = "plan_id")
String planId;
//TODO : Replace with Context class when the spec defines things clearly
@JsonProperty(value = "context")
Object context;
@JsonProperty(value = "organization_guid")
String organizationGuid;
@JsonProperty(value = "space_guid")
String spaceGuid;
@JsonProperty(value = "parameters")
Parameters parameters;
}

参数

    public class Parameters {
@JsonProperty(value = "agent_name")
String agentName;
@JsonProperty(value = "url")
String url;
@JsonProperty(value = "credential")
String credential;
@JsonProperty(value = "ia_url")
String iaUrl;
}

我使用@JsonProperty到处。有没有办法将下划线分隔的json键放入java的变量命名约定(Camelcase)中?

我尝试使用@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)到我的 POJO 类而不是 @JsonProperty对于每个参数。我只是得到一个空的 json {}instance 。我在这里缺少什么?

最佳答案

是的,通过 JsonNaming 注释使用 PropertyNamingStrategy 类是否可以实现这一点

例如:

@JsonNaming(PropertyNamingStartergy.LowerCaseWithUnderscoresStrategy.class)
class Class_name{
...
}

//----以下代码已更新。在该代码中我使用

PropertyNamingStrategy.SnakeCaseStrategy

工作代码(已测试)。

getter 和 setter 对于此工作非常重要。但 @JsonProperty 不需要它们

用户.java

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class User {
private int id;
private String beanName;
private Role role;


public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}

}

角色.java

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Role {
private int id;
private String roleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}

}

这是 Controller

@RestController
@RequestMapping("/test")
public class NamingController {

@RequestMapping(value="/jsontopojo", method = RequestMethod.POST)
public ResponseEntity<User> jsontopojo(@RequestBody User nam) {
return new ResponseEntity<User>( nam, HttpStatus.OK);
}

}

enter image description here

关于java - 复杂 Json 到嵌套 POJO spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48781339/

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