在scala中删除JSON数组元素

时间:2016-05-23 06:21:03

标签: arrays json scala rest playframework

我有这样的JSON结果:

[
    {
        "id": 2202,
        "name": "name one",
        "phone": "+62888888",
        "email": "customer@gmail.com",
        "corporateId": null,
        "corporateName": null,
        "version": 119,
        "signupDate": "2016-01-28T00:00:00+07:00"
    },
    {
        "id": 2580,
        "name": "name two",
        "phone": "+628777777",
        "email": "customer2@gmail.com",
        "corporateId": null,
        "corporateName": null,
        "version": 119,
        "signupDate": "2016-01-28T00:00:00+07:00"
    }
]

如何删除某些元素,以便我有这样的新JSON结果(删除corporateIdcorporateName):

[
    {
        "id": 2202,
        "name": "name one",
        "phone": "+62888888",
        "email": "customer@gmail.com",
        "version": 119,
        "signupDate": "2016-01-28T00:00:00+07:00"
    },
    {
        "id": 2580,
        "name": "name two",
        "phone": "+628777777",
        "email": "customer2@gmail.com",
        "version": 119,
        "signupDate": "2016-01-28T00:00:00+07:00"
    }
]

1 个答案:

答案 0 :(得分:1)

有一些方法。其中一个JSON transformers

要删除corporateIdcorporateName,请使用Case 6: Prune a branch from input JSON

(__ \ "corporateId").json.prune andThen (__ \ "corporateName").json.prune

要删除每个JsArray元素,请使用Reads.list

Reads.list(
  (__ \ "corporateId").json.prune andThen (__ \ "corporateName").json.prune
)

复杂的变压器将是:

json.transform(
  Reads.list(
    (__ \ "corporateId").json.prune andThen (__ \ "corporateName").json.prune
  ).map(JsArray)
)

res3: play.api.libs.json.JsResult[play.api.libs.json.JsArray] = JsSuccess([{"id":2202,"name":"name one","phone":"+62888888","email":"customer@gmail.com","version":119,"signupDate":"2016-01-28T00:00:00+07:00"},{"id":2580,"name":"name two","phone":"+628777777","email":"customer2@gmail.com","version":119,"signupDate":"2016-01-28T00:00:00+07:00"}],)