Parse Json List with 1 item (Scala / liftweb)

I am facing a situation where I am retrieving Json from an external server (I have no control over this server). Json has one element that can happen 1 or more times. I am trying to parse it using net.liftweb.json, and this only works fine if the element occurs more than once. If an element occurs only once, it is not parsed.

Here is a sample code:

import net.liftweb.json._
import net.liftweb.json.JsonDSL._

case class JSonListIssue(foo: List[String])

class JSonTest extends TestCase {

  implicit val formats = net.liftweb.json.DefaultFormats; 

  def testJsonList {
    val jsonStr2Foos = "{\"foo\": \"bar\", \"foo\": \"bar2\"}"
    val json = (parse(jsonStr2Foos).extract[JSonListIssue]) 
    assertEquals(2, json.foo.size)

    val jsonStr1Foo = "{\"foo\": \"bar\"}"
    val json2 = (parse(jsonStr1Foo).extract[JSonListIssue]) // Results in Json MappingException
    assertEquals(1, json2.foo.size)
  }

}

In the above code, the second argument to the analysis does not work. If I defined the case class as follows, the second parsing would work, but the first would not be executed.

    case class JSonListIssue(foo: String)

Any suggestions on how to solve this in a clean way? I could, of course, catch a MappingException and then parse it using another case class, but this one is dirty ...

Thanks Hero

+5
1

, , , API, , - , - .: P

, , , -, . JValue, JSON \.

, - .

case class JsonListIssue(foo: List[String])

def extractJsonListIssue(json: JValue) = {
  json \ "foo" match {
    case JString(foo) =>
      JsonListIssue(List(foo))

    case _ =>
      json.extract[JsonListIssue]
  }
}

json \ "foo" . ! , . FWIW, Lift-y, Box tryo, Failure, . , :

// Add these guys to your existing imports
import net.liftweb._
  import common._
  import util.Helpers._

case class JsonListIssue(foo: List[String])

def extractJsonListIssue(json: JValue) = {
  json \ "foo" match {
    case JString(foo) =>
      Full(JsonListIssue(List(foo)))

    case _ =>
      // Will return a Full with the result of the method on
      // success and a Failure if extract throws an exception.
      tryo(json.extract[JsonListIssue])
  }
}

.

, . , - . , !

0

All Articles