2017-05-14 27 views
0

我正在使用akka与喷射json支持,我需要在接收的json中编辑值。如何使用sprayJSON编辑现有的JSON对象

import akka.http.scaladsl.server.Directives 
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport 
import spray.json._ 


final case class Item(name: String, id: Long) 
final case class Order(items: List[Item],orderTag:String) 


trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol { 
    implicit val itemFormat = jsonFormat2(Item) 
    implicit val orderFormat = jsonFormat2(Order) 
} 

在我的使用情况下,我收到与orderTag一个空值的JSON,我需要做的是与编辑orderTag值,然后将其作为实体value.Is有可能写/编辑的JSONObject和如何要做到这一点 ?

class MyJsonService extends Directives with JsonSupport { 

    // format: OFF 
    val route = 
    get { 
     pathSingleSlash { 
     complete(Item("thing", 42)) // will render as JSON 
     } 
    } ~ 
    post { 
     entity(as[Order]) { order => // will unmarshal JSON to Order 
     val itemsCount = order.items.size 
     val itemNames = order.items.map(_.name).mkString(", ") 
     complete(s"Ordered $itemsCount items: $itemNames") 
     } 
    } 

} 

回答

0

您只需编辑JSON AST如..

val json = """{"orderTag":null}""" 
val jsVal = json.parseJson 
val updatedJs = if (jsObj.fields.get("orderTag") == Some(JsNull)) { 
JsObject(jsObj.fields + ("orderTag" -> JsString("new tag"))) 
} else { 
    jsObj 
} 
updatedJs.compactPrint 
res26: String = """ 
{"orderTag":"new tag"} 
"""