summaryrefslogtreecommitdiff
path: root/src/main/scala/io/trygvis/cj/Json4sHelpers.scala
blob: 0241e590113262cb49b5f9f6618f839eb4124e12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package io.trygvis.cj

import org.json4s._

object Json4sHelpers {
  def getAsObjectList(obj: JObject, name: String): List[JObject] = {
    (obj \ name) match {
      case JArray(values) => values.collect{case o@JObject(_) => o}
      case o@JObject(_) => List(o)
      case _ => Nil
    }
  }

  def getAsValueList(obj: JObject, name: String): List[JValue] = {
    (obj \ name) match {
      case JNothing => Nil
      case JArray(values) => values
      case j => List(j)
    }
  }

  def getAsObject(obj: JObject, name: String): Option[JObject] = {
    (obj \ name) match {
      case o@JObject(_) => Some(o)
      case _ => None
    }
  }

  def getAsString(obj: JObject, name: String): Option[String] = {
    (obj \ name) match {
      case JString(s) => Some(s)
      case _ => None
    }
  }

  def replace(obj: JObject, name: String, value: JValue): JObject = {
    val map = obj.obj.toMap - name
    JObject(map.updated(name, value).toList)
  }

  def filtered(obj: JObject): JObject = {
    JObject(obj.obj.filter {
      case JField(_, JNothing) => false
      case _ => true
    })
  }
}