1. 程式人生 > >akka http複雜格式json處理

akka http複雜格式json處理

package com.example

import spray.json._

case class Color( name: String, red: Double, green: Int, blue: Int )
case class Colors( colors: List[Color] )
case class Paint( name: String, colors: Colors )

object MyJsonProtocol extends DefaultJsonProtocol {
    implicit val colorFormat = jsonFormat4( Color
) //4個屬性 implicit val colorsFormat = jsonFormat1( Colors ) //1個屬性 implicit val paintFormat = jsonFormat2( Paint ) //2個屬性 } /** * Author: zhouhh * Date: 2017.7.15 * 抽象語法樹結構(Abstract Syntax Tree (AST)), 是Json物件樹, 區別於json字串和模型物件 * 該程式碼演示三者之間互轉. 但引入複雜物件,浮點和集合 * */ object TestSprayJsonConvert { import
MyJsonProtocol._ def main( args: Array[String] ): Unit = { //object to jsonAst, 軍校藍, 此處故意調整值為浮點 val json = Color( "CadetBlue", 95.2, 158, 160 ).toJson println( json ) //{"name":"CadetBlue","red":95,"green":158,"blue":160} //jsonAst to object val color = json.convertTo
[Color] println( "name:" + color.name + ",red:" + color.red + ",green:" + color.green + ",blue:" + color.blue ) //name:CadetBlue,red:95,green:158,blue:160 val jsonsListStr = "[{\"name\":\"CadetBlue\",\"red\":95.3,\"green\":158,\"blue\":160},{\"name\":\"CadetRed\",\"red\":160.5,\"green\":158,\"blue\":95}]" //另一種更直觀的表示 val jsons = """{"colors":[{"name":"CadetBlue","red":95.3,"green":158,"blue":160},{"name":"CadetRed","red":160.5,"green":158,"blue":95}]}""" //string -> jsonAst(JsValue) -> object val colorsObj: Colors = jsons.parseJson.convertTo[Colors] print( colorsObj ) val colorsList: List[Color] = jsonsListStr.parseJson.convertTo( DefaultJsonProtocol.listFormat[Color] ) //此處故意將colorsObj命名有區別,否則出現兩個colors, 後者是前者的成員. colorsObj.colors.foreach { color => println( "name:" + color.name + ",red:" + color.red + ",green:" + color.green + ",blue:" + color.blue ) } //do the same thing but directly var List colorsList.foreach { color => println( "name:" + color.name + ",red:" + color.red + ",green:" + color.green + ",blue:" + color.blue ) } //object -> json // val listjson = colors.colors.toArray.toJson val listjson: JsValue = colorsObj.toJson println( listjson ) //複雜結構, json字串,物件互轉. val paintJsonStr = """ {"name":"mypaint","colors":{"colors":[{"name":"CadetBlue","red":95.3,"green":158,"blue":160},{"name":"CadetRed","red":160.5,"green":158,"blue":95}]}}""" val paintAST = paintJsonStr.parseJson val paint: Paint = paintAST.convertTo[Paint] val paintJsonStrTo = paint.toJson println( paintAST ) println( paint ) println( paintJsonStrTo ) } }