java json injection_使用Jackson基于条件注入json属性

我使用Jackson API将json格式转换为Java对象模型。我正在使用Jaxsonxml 2.1.5解析器。 json响应如下所示。使用Jackson基于条件注入json属性

{

"response": {

"name": "states",

"total-records": "1",

"content": {

"data": {

"name": "OK",

"details": {

"id": "1234",

"name": "Oklahoma"

}

}

}

}

}

现在json响应格式已经改变。如果total-records为1,则details将是具有id和name属性的对象。但如果total-records超过1那么details将对象的数组象下面这样:

{

"response": {

"name": "states",

"total-records": "4",

"content": {

"data": {

"name": "OK",

"details": [

{

"id": "1234",

"name": "Oklahoma"

},

{

"id": "1235",

"name": "Utah"

},

{

"id": "1236",

"name": "Texas"

},

{

"id": "1237",

"name": "Arizona"

}

]

}

}

}

}

我的Java类映射看起来像下面与早期json响应。

@JsonIgnoreProperties(ignoreUnknown = true)

public class MapModelResponseList {

@JsonProperty("name")

private String name;

@JsonProperty("total-records")

private String records;

@JsonProperty(content")

private Model model;

public Model getModelResponse() {

return model;

}

public void setModel(Model model) {

this.model = model;

}

}

客户端代码

package com.test.deserializer;

import com.fasterxml.jackson.databind.DeserializationFeature;

import com.fasterxml.jackson.databind.ObjectMapper;

import com..schema.model.Person;

public class TestClient {

public static void main(String[] args) {

String response1="{\"id\":1234,\"name\":\"Pradeep\"}";

TestClient client = new TestClient();

try {

Person response = client.readJSONResponse(response1, Person.class);

} catch (Exception e) {

e.printStackTrace();

}

}

public T readJSONResponse(String response, Class type) {

ObjectMapper mapper = new ObjectMapper();

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

T result = null;

try {

result = mapper.readValue(response, type);

} catch (Exception e) {

e.printStackTrace();

}

return (T) result;

}

}

现在基础上,total-records如何处理对映射到任何Model对象的Model或列表。请告诉我。

2016-07-31

zilcuanu

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值