【发布时间】:2018-04-04 14:40:47
【问题描述】:
我必须将特定的 JSON 响应转换为其他格式
例如我的输入 JSON 就像
JSON1
[
{
"propertyId":10081,
"roomId":0,
"startDate":"2018-01-29T00:00:00",
"endDate":"2018-01-30T00:00:00",
"priority":1,
"message":"Test it",
"id":158,
"dateModifiedUtc":null
},
{
"propertyId":10081,
"roomId":10021855,
"startDate":"2018-01-29T00:00:00",
"endDate":"2018-01-30T00:00:00",
"priority":2,
"message":"Check how it works",
"id":159,
"dateModifiedUtc":null
},
{
"propertyId":10081,
"roomId":10021855,
"startDate":"2018-01-29T00:00:00",
"endDate":"2018-01-30T00:00:00",
"priority":2,
"message":"Check how it works",
"id":160,
"dateModifiedUtc":null
}
]
我需要替换 roomId 的一些值,然后将 json 转换为以下格式并将其发送到其他端点
JSON2
{
"sitenotification":[
{
"roomid":"10601",
"priority":1,
"startdate":"2017-08-10T15:50:52+03:00",
"enddate":"2017-08-15T15:50:52+03:00",
"sitemessage":"test"
},
{
"roomid":"10601",
"priority":1,
"startdate":"2017-08-10T15:50:52+03:00",
"enddate":"2017-08-15T15:50:52+03:00",
"customermessage":"test 2"
}
]
}
我尝试通过几种方式来做到这一点,例如使用 jackson 进行反序列化并将其映射到下面的特定类
@JsonIgnoreProperties(ignoreUnknown = true)
public class FatNotificationsAttributesDataModel {
@JsonProperty("propertyId")
public int propertyId;
@JsonProperty("roomId")
public int roomId;
@JsonProperty("startDate")
public String startDate;
@JsonProperty("endDate")
public String endDate;
@JsonProperty("priority")
public int priority;
@JsonProperty("message")
public String message;
@JsonProperty("id")
public int id;
@JsonProperty("dateModifiedUtc")
public String dateModifiedUtc;
}
然后再次使用不同的类对其进行序列化
@JsonSerialize(using = CustomSerializer.class)
public class FinalDataModel {
public int roomId;
public String startDate;
public String endDate;
public int priority;
public String message;
}
但不知何故,转换不起作用。我们有更好的方法来实现这一目标吗?
【问题讨论】:
-
你能澄清什么不起作用吗?是否有任何异常或输出与您期望得到的不同?
-
使用gson,它会让你的生活更轻松
-
您的输入不一定是
Json。它是Json元素的数组。尝试反序列化为ArrayList<FatNotificationsAttributesDataModel>,看看是否可行。 -
抱歉我的描述不够好。我可以通过使用类似 List
attributes = node.findValues("attributes"); 的东西将 JSON1 反序列化为列表。 pojo = mapper.convertValue(属性, FatNotificationsAttributesDataModel[].class); .但我不确定如何从对象列表中获取 JSON2,我不太确定我遵循的方法
标签: java json objectmapper jackson-databind