Put Data in mutlple branch of Array : Json Transformer ,Scala Play

时间:2016-10-20 18:53:20

标签: json scala playframework-2.0 transformation

i want to add values to all the arrays in json object.

For eg:

value array [4,2.5,2.5,1.5] json =

{
  "items": [
    {
      "id": 1,
      "name": "one",
      "price": {}
    },
    {
      "id": 2,
      "name": "two"
    },
    {
      "id": 3,
      "name": "three",
      "price": {}
    },
    {
      "id": 4,
      "name": "four",
      "price": {
        "value": 1.5
      }
    }
  ]
}

i want to transform the above json in

{
  "items": [
    {
      "id": 1,
      "name": "one",
      "price": {
        "value": 4
      }
    },
    {
      "id": 2,
      "name": "two",
      "price": {
        "value": 2.5
      }
    },
    {
      "id": 3,
      "name": "three",
      "price": {
        "value": 2.5
      }
    },
    {
      "id": 4,
      "name": "four",
      "price": {
        "value": 1.5
      }
    }
  ]
}

Any suggestions on how do i achieve this. My goal is to put values inside the specific fields of json array. I am using play json library throughout my application. What other options do i have instead of using json transformers.

2 个答案:

答案 0 :(得分:2)

您可以使用简单的转换,例如

val prices = List[Double](4,2.5,2.5,1.5).map(price => Json.obj("price" -> Json.obj("value" -> price)))

val t = (__ \ "items").json.update(
  of[List[JsObject]]
    .map(_.zip(prices).map(o => _._1 ++ _._2))
    .map(JsArray)
)

res5: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"items":[{"id":1,"name":"one","price":{"value":4}},{"id":2,"name":"two","price":{"value":2.5}},{"id":3,"name":"three","price":{"value":2.5}},{"id":4,"name":"four","price":{"value":1.5}}]},/items)

答案 1 :(得分:0)

我建议使用类,但不确定这是否适合您的项目,因为很难猜出整个代码的样子。
为简单起见,我手动设置了new Item。您可以使用Json库创建items:)

class Price(val value:Double) {
    override def toString = s"{value:${value}}"
}

class Item(val id: Int, val name: String, val price: Price) {
    def this(id: Int, name: String) {
      this(id, name, null)
    }

    override def toString = s"{id:${id}, name:${name}, price:${price}}"
}

val price = Array(4, 2.5, 2.5, 1.5)

/** You might convert Json data to List[Item] using Json library instead. */
val items: List[Item] = List(
    new Item(1, "one"),
    new Item(2, "two"),
    new Item(3, "three"),
    new Item(4, "four", new Price(1.5))
)

val valueMappedItems = items.zipWithIndex.map{case (item, index) =>
    if (item.price == null) {
      new Item(item.id, item.name, new Price(price(index)))
    } else {
      item
    }
}