converting from Java script Json to Scala Json without eleminating field name for update operation

60 views Asked by At

I use a function to convert from a json information sent from the front end:

  def convertFromJson(json: JsValue): Item = {

Item(
  (json \ "id").asOpt[String],
  (json \ "name").asOpt[String],
  (json \ "project").asOpt[String],
  (json \ "price").asOpt[scala.math.BigDecimal],
  if ((json \ "quantity").asOpt[String].contains("NaN"))
    { 
        None 
    } 
  else 
    {
        (json \ "quantity").asOpt[scala.math.BigDecimal]

    }
)

  }    

If a normal number like 2.0 for the quantity field is entered then I wll be able to see a json object like:

{"id":"5aa7367","quantity":2}

The problem is that if my front end sends a NaN value to the back end for the Quantity field then I get:

{"id":"5aa7367"}

Is there a way to have something like {"id":"5aa7367","quantity":None}. Quantity has been declared as BigDecimal.

1

There are 1 answers

7
Ossip On

I guess you figured it out otherwise, but here's my take - the quantity seems to get returned as empty for NaN case, so you should simply get None ?

  if ((json \ "quantity").asOpt[Int].isEmpty)