title: How do you write a json4s CustomSerializer that handles collections
body: <p>I have a class that I am trying to deserialize using the json4s <code>CustomSerializer</code> functionality.  I need to do this due to the <a href="https://github.com/json4s/json4s/issues/138" rel="nofollow">inability of json4s to deserialize mutable collections</a>.</p>
  
  <p>This is the basic structure of the class I want to deserialize (don't worry about why the class is structured like this):</p>
  
  <pre><code>case class FeatureValue(timestamp:Double)
  
  object FeatureValue{
    implicit def ordering[F &lt;: FeatureValue] = new Ordering[F] {
      override def compare(a: F, b: F): Int = {
        a.timestamp.compareTo(b.timestamp)
      }
    }
  }
  
  class Point {
    val features = new HashMap[String, SortedSet[FeatureValue]]
  
    def add(name:String, value:FeatureValue):Unit = {
      val oldValue:SortedSet[FeatureValue] = features.getOrElseUpdate(name, SortedSet[FeatureValue]())
      oldValue += value
    }
  }
  </code></pre>
  
  <p>Json4s serializes this just fine.  A serialized instance might look like the following:</p>
  
  <pre><code>{"features":
    {
     "CODE0":[{"timestamp":4.8828914447482E8}],
     "CODE1":[{"timestamp":4.8828914541333E8}],
     "CODE2":[{"timestamp":4.8828915127325E8},{"timestamp":4.8828910097466E8}]
    }
  }
  </code></pre>
  
  <p>I've tried writing a custom deserializer, but I don't know how to deal with the list tails.  In a normal matcher you can just call your own function recursively, but in this case the function is anonymous and being called through the json4s API.  I cannot find any examples that deal with this and I can't figure it out.</p>
  
  <p>Currently I can match only a single hash key, and a single <code>FeatureValue</code> instance in its value.  Here is the CustomSerializer as it stands:</p>
  
  <pre><code>import org.json4s.{FieldSerializer, DefaultFormats, Extraction, CustomSerializer}
  import org.json4s.JsonAST._
  
  class PointSerializer extends CustomSerializer[Point](format =&gt; (
    {
      case JObject(JField("features", JObject(Nil)) :: Nil) =&gt; new Point
      case JObject(List(("features", JObject(List(
        (feature:String, JArray(List(JObject(List(("timestamp",JDouble(ts)))))))))
      ))) =&gt; {
        val point = new Point
        point.add(feature, FeatureValue(ts))
        point
      }
    },
    {
      // don't need to customize this, it works fine
      case x: Point =&gt; Extraction.decompose(x)(DefaultFormats + FieldSerializer[Point]())
    }
    ))
  </code></pre>
  
  <p>If I try to change to using the :: separated list format, so far I have gotten compiler errors.  Even if I didn't get compiler errors, I am not sure what I would do with them.</p>