我的对象具有以下结构:
class MyObject{
private String firstString;
private BigDecimal bigDecimal;
private NestedObject nestedObject;
private Map<String, String> map;
}
我想通过 Postman 在下面的POST
下创建一个JSON
呼叫:
{
"firstString": "first",
"bigDecimal": 1.2222,
"nestedObject": {
"secondString": "second"
},
"param1": "paramValue1",
"param2": "paramValue2",
"param3": "paramValue3"
}
我也尝试过:
{
"firstString": "first",
"bigDecimal": 1.2222,
"nestedObject": {
"secondString": "second"
},
"customMap" :{
"param1": "paramValue1",
"param2": "paramValue2",
"param3": "paramValue3"
}
}
我想将param1
,param2
,param3
视为Map
键-值,因为参数是未知的(元素的数量可以是1或1000),我想将其解析为收到此正文后的步骤之一。
NestedObject
是具有已知结构的完全嵌套的对象。
@POST
@Path("/")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String getEntity( MyObject myObject){
//sth
}
当我在调用后完全按照上面的方法进行操作时,我得到Object,但map变量为null。我该如何解决这个问题,您有什么想法吗?
编辑其他信息: @lealceldeiro在下面,您可以找到我的代码,是否有任何“可疑”部分?
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
class SearchParamsFromRequest {
private NestedObject nestedObject;
private String surname;
private String type;
private String userName;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<>();
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
@POST
@Path("/")
@Consumes({MediaType.APPLICATION_JSON})
public String getString (SearchParamsFromRequest searchParameters){
return "Any String";
}
答案 0 :(得分:1)
您可以使用com.fasterxml.jackson.annotation来做到这一点。
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class MyObject {
private String firstString;
private BigDecimal bigDecimal;
private NestedObject nestedObject;
@JsonIgnore
private Map<String, Object> map = new HashMap<>();
// you can change it to Map<String, String> if you know they will always
// be string - string, be consistent with `setAdditionalProperty`
@JsonAnyGetter
public Map<String, Object> getMap() {
return this.map;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.map.put(name, value);
}
// getters and setters omitted
// REMEMBER to follow the java beans naming conventions
// for example call the setters and getters such as `setFirstName` and `getFirstName` for the `firstName` attribute
}
此(http://www.jsonschema2pojo.org/)可以帮助您从JSON等来源获取类。