未从内部类的json请求填充Java对象

时间:2018-05-30 16:13:12

标签: java json

已经在不同的网站搜索过但找不到正确的答案,因此发布此请求虽然可能会重复该网页。

我将以下json请求发送到我的后端服务并转换为java对象进行处理。我可以看到请求体传递给我的服务但是当我从json转换为java对象时,值不会填充

{  
  "data":{  
  "username":"martin",
  "customerId":1234567890,
  "firstName":"john",
  "lastName":"smith",
  "password":"p@ssrr0rd@#12",
  "email":"john.smith@gmail.com",
  "contactNumber":"0342323443",
  "department":"sports",
  "location":"texas",
  "status":"unlocked",
  "OrderConfigs":[  
        {  
           "vpnId":"N4234554R",
           "serviceId":"connectNow",
           "serviceType":"WRLIP",
           "ipAddress":"10.101.10.3",
           "fRoute":[  
             "10.255.253.0/30",
             " 10.255.254.0/30"
            ],
         "timeout":1800,
         "mapId":"test_map"
       }
     ]
   }
 }

My Parser类有类似的东西,

      JSONObject requestJSON = new JSONObject(requestBody).getJSONObject("data");
        ObjectMapper mapper = new ObjectMapper();
        final String jsonData = requestJSON.toString();
        OrderDTO mappedObject= mapper.readValue(jsonData , OrderDTO .class);
    // I can see value coming from front-end but not populating in the mappedObject

我的OrderDTO.java

  @JsonInclude(value = Include.NON_NULL)
  @JsonIgnoreProperties(ignoreUnknown = true,value = {"hibernateLazyInitializer", "handler", "created"})
 public class OrderDTO {

 private String username;
 private long customerId;
 private String source;    
 private String firstName; 
 private String lastName;    
 private String email;  
 private String contactNumber;
 private String password;    
 private String department;    
 private String location;    
 private String status;
 private List<OrderConfig> OrderConfigs;

 @JsonInclude(value = Include.NON_NULL)
  public class OrderConfig {

    private String vpnId;
    private String serviceId;
    private String serviceType;
    private String ipAddress;      
    private String mapId;         
    private String[] fRoutes;
    private Map<String, Object> attributes;
    private SubConfig subConfig;
    private String routeFlag;

   getter/setters
    .....
   }
  all setter/getter
 }

不确定我在这里缺少什么。这是正确的方法吗?

2 个答案:

答案 0 :(得分:0)

OrderConfigs字段不会被初始化,只需将您的bean修改为

@JsonProperty("OrderConfigs")
private List<OrderConfig> orderConfigs;

// setter and getter as setOrderConfigs / getOrderConfigs

请参阅我的回答here。 (同一期)

答案 1 :(得分:0)

如果您正在尝试使用内部类,正确的使用方法是将Jackson声明为静态以使用内部类。 供参考检查this

代码更改

@JsonInclude(value = Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) static class OrderConfig {

确保您的json标记名称与java对象的变量名称匹配

Ex:“fRoute”:[
             “10.255.253.0/30”              “10.255.254.0/30”             ],

private String [] fRoutes;