Scala JSON如果键匹配值返回字符串

时间:2020-03-30 06:29:48

标签: scala lift-json

我有如下所示的JSon响应。 如果元数据的Organic = true,则label ='true-Organic',否则label ='non-Organic' 最后=>返回List或Map [modelId,label]

import net.liftweb.json.{DefaultFormats, _}


object test1 extends App {

  val json_response =
    """{
  "requestId": "91ee60d5f1b45e#316",
  "error": null,
  "errorMessages": [
  ],
  "entries": [

  {

    "modelId":"RT001",
    "sku": "SKU-ASC001",
    "store": "New Jersey",
    "ttlInSeconds": 8000,
    "metadata": {
      "manufactured_date": "2019-01-22T01:25Z",
      "organic": "true"
    }
  },
  {

    "modelId":"RT002",
    "sku": "SKU-ASC002",
    "store": "livingstone",
    "ttlInSeconds": 8000,
    "metadata": {
      "manufactured_date": "2019-10-03T01:25Z",
      "organic": "false"
    }
  }

  ] }"""

这样尝试:

 val json = parse(json_response)
  implicit val formats = DefaultFormats
  var map = Map[String, String]()

  case class Sales(modelId: String, sku: String, store: String, ttlInSeconds: Int, metadata:
  Map[String, String])

  case class Response(entries: List[Sales])

  val response = json.extract[Response]

此后,不确定如何继续。

1 个答案:

答案 0 :(得分:1)

这是<head> <title>question3</title> </head> <body> <form> name:<input type="text" name="hjcg"><p style="text-align: right">jgdfiuhio hjgiofhuorgfo gfd7uyte8u7tr98gt</p> username::<input type="text" name="hjcg"><span style="text-align: right">hjgdfiuhio hjgiofhuorgfo gfd7uyte8u7tr98gt</span> </body> </html>![enter image description here](https://i.stack.imgur.com/OCSnC.jpg)![enter image description here](https://i.stack.imgur.com/XQkvB.jpg) 字段上的简单map操作:

entries

这将返回response.entries.map{ e => e.modelId -> if (e.metadata.get("organic").contains("true")) { "true-Organic" } else { "non-Organic" } } ,但是如果需要,您可以调用List[(String, String)]将其变成toMap

相关问题