在Java中将JSON从一种格式转换为另一种JSON格式

问题描述 投票:1回答:2

我必须转换特定的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;

}

但不知何故转换不起作用。我们有更好的方法来实现这一目标吗?

java json objectmapper jackson-databind
2个回答
0
投票

您可以使用JSONObject和JSONArray来实现

//Create a JSON array with your json string
JSONArray array = new JSONArray(jsonString);
JSONArray newArray = new JSONArray();
//loop on your JSONArray elements
for (i=0, i<array.size(),i++) {
    //Get each separate object into a JSONObject
    JSONObject obj = array.getJSONObject(i);
    //let say you want to modify id for example
    obj.put("id", 12345);
    //push the modifyed object into your new array
    newArray.put(obj);
}
//transform the array into a string
String json = newArray.toString();

0
投票

使用Jolt Convertor。将任何JSON转换为任何其他JSON格式的最简单,最简单的方法。

https://jolt-demo.appspot.com/#inception

© www.soinside.com 2019 - 2024. All rights reserved.