alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Lift Framework example source code file (XmlExamples.scala)

This example Lift Framework source code file (XmlExamples.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Lift Framework tags/keywords

dave, david, harry, jarray, jfield, jfield, jnothing, jnothing, jobject, jobject, jstring, jstring, jvalue, nil

The Lift Framework XmlExamples.scala source code

/*
 * Copyright 2009-2011 WorldWide Conferencing, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.liftweb
package json

import org.specs.Specification


/**
 * System under specification for Xml Examples.
 */
object XmlExamples extends Specification("XML Examples") {
  import JsonDSL._
  import Xml._
  import scala.xml.{Group, Text}

  "Basic conversion example" in {
    val json = toJson(users1) 
    compact(render(json)) mustEqual """{"users":{"count":"2","user":[{"disabled":"true","id":"1","name":"Harry"},{"id":"2","name":"David","nickname":"Dave"}]}}"""
  }

  "Conversion transformation example 1" in {
    val json = toJson(users1).transform {
      case JField("id", JString(s)) => JField("id", JInt(s.toInt))
    }
    compact(render(json)) mustEqual """{"users":{"count":"2","user":[{"disabled":"true","id":1,"name":"Harry"},{"id":2,"name":"David","nickname":"Dave"}]}}"""
  }

  "Conversion transformation example 2" in {
    val json = toJson(users2).transform {
      case JField("id", JString(s)) => JField("id", JInt(s.toInt))
      case JField("user", x: JObject) => JField("user", JArray(x :: Nil))
    }
    compact(render(json)) mustEqual """{"users":{"user":[{"id":1,"name":"Harry"}]}}"""
  }

  "Primitive array example" in {
    val xml = <chars>abc
    compact(render(toJson(xml))) mustEqual """{"chars":{"char":["a","b","c"]}}"""
  }

  "Lotto example which flattens number arrays into encoded string arrays" in {
    def flattenArray(nums: List[JValue]) = JString(nums.map(_.values).mkString(","))

    val printer = new scala.xml.PrettyPrinter(100,2)
    val lotto: JObject = LottoExample.json
    val xml = toXml(lotto.transform {
      case JField("winning-numbers", JArray(nums)) => JField("winning-numbers", flattenArray(nums))
      case JField("numbers", JArray(nums)) => JField("numbers", flattenArray(nums))
    })

    printer.format(xml(0)) mustEqual printer.format(
      <lotto>
        <id>5
        <winning-numbers>2,45,34,23,7,5,3
        <winners>
          <winner-id>23
          <numbers>2,45,34,23,3,5
        </winners>
        <winners>
          <winner-id>54
          <numbers>52,3,12,11,18,22
        </winners>
      </lotto>)
  }

  "Band example with namespaces" in {
    val json = toJson(band)
    json mustEqual parse("""{
  "b:band":{
    "name":"The Fall",
    "genre":"rock",
    "influence":"",
    "playlists":{
      "playlist":[{
        "name":"hits",
        "song":["Hit the north","Victoria"]
      },{
        "name":"mid 80s",
        "song":["Eat your self fitter","My new house"]
      }]
    }
  }
}""")
  }

  val band =
    <b:band>
      <name>The Fall
      <genre>rock
      <influence/>
      <playlists>
        <playlist name="hits">
          <song>Hit the north
          <song>Victoria
        </playlist>
        <playlist name="mid 80s">
          <song>Eat your self fitter
          <song>My new house
        </playlist>
      </playlists>
    </b:band>

  "Grouped text example" in {
    val json = toJson(groupedText)
    compact(render(json)) mustEqual """{"g":{"group":"foobar","url":"http://example.com/test"}}"""
  }

  val users1 =
    <users count="2">
      <user disabled="true">
        <id>1
        <name>Harry
      </user>
      <user>
        <id>2
        <name nickname="Dave">David
      </user>
    </users>   

  val users2 =
    <users>
      <user>
        <id>1
        <name>Harry
      </user>
    </users>

  val url = "test"
  val groupedText =
    <g>
      <group>{ Group(List(Text("foo"), Text("bar"))) }
      <url>http://example.com/{ url }
    </g>

  // Examples by Jonathan Ferguson. See http://groups.google.com/group/liftweb/browse_thread/thread/f3bdfcaf1c21c615/c311a91e44f9c178?show_docid=c311a91e44f9c178
  // This example shows how to use a transformation function to correct JSON generated by
  // default conversion rules. The transformation function 'attrToObject' makes following conversion:
  // { ..., "fieldName": "", "attrName":"someValue", ...}      ->
  // { ..., "fieldName": { "attrName": f("someValue") }, ... }
  def attrToObject(fieldName: String, attrName: String, f: JString => JValue)(json: JValue) = json.transform {
    case JField(n, v: JString) if n == attrName => JObject(JField(n, f(v)) :: Nil)
    case JField(n, JString("")) if n == fieldName => JNothing
  } transform {
    case JField(n, x: JObject) if n == attrName => JField(fieldName, x)
  }

  "Example with multiple attributes, multiple nested elements " in  {  
    val a1 = attrToObject("stats", "count", s => JInt(s.s.toInt)) _
    val a2 = attrToObject("messages", "href", identity) _
    val json = a1(a2(toJson(messageXml1)))
    (json diff parse(expected1)) mustEqual Diff(JNothing, JNothing, JNothing)
  }

  "Example with one attribute, one nested element " in { 
    val a = attrToObject("stats", "count", s => JInt(s.s.toInt)) _
    compact(render(a(toJson(messageXml2)))) mustEqual expected2
    compact(render(a(toJson(messageXml3)))) mustEqual expected2
  }

  val messageXml1 = 
    <message expiry_date="20091126" text="text" word="ant" self="me">
      <stats count="0">
      <messages href="https://domain.com/message/ant">
    </message>

  val expected1 = """{"message":{"expiry_date":"20091126","word":"ant","text":"text","self":"me","stats":{"count":0},"messages":{"href":"https://domain.com/message/ant"}}}"""

  val messageXml2 = 
    <message expiry_date="20091126">
      <stats count="0">
    </message>

  val messageXml3 = <message expiry_date="20091126">

  val expected2 = """{"message":{"expiry_date":"20091126","stats":{"count":0}}}"""
}

Other Lift Framework examples (source code examples)

Here is a short list of links related to this Lift Framework XmlExamples.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.