scalalift-json

Scala How to convert JsonAST.JValue to a type?


I have an angular app that POSTs a request to the server like so:

$scope.downloadPartDetails = (parts, e) ->
    req = {
      method: 'POST',
      url: '/downloads/partdetails',
      headers: {
        'Content-Type': "application/json; charset=utf-8"
      },
      data: { parts: [
        {manufacturer: "mfr1", partNumber: "part num1"},
        {manufacturer: "mfr2", partNumber: "part num2"},
        {manufacturer: "mfr3", partNumber: "part num3"}
      ] }
    }
    $http(req)

It shows up on server like this:

JArray(List(JObject(List(JField(manufacturer,JString(mfr1)), JField(partNumber,JString(part num1)))), JObject(List(JField(manufacturer,JString(mfr2)), JField(partNumber,JString(part num2)))), JObject(List(JField(manufacturer,JString(mfr3)), JField(partNumber,JString(part num3))))))

Is there a way to convert this to a List[Part]?

case class Part(mfr: String, pn: String)

Solution

  • It would be easier if you use the same field names in the json and in the case class

    case class Part(manufacturer: String, partNumber: String)
    val part: Part = jvalue.extract[Part]
    

    if you can't change the field names in your case class you will need to implement a custom serializer as explained here Deserialization of case object in Scala with JSON4S