如何保留scala和Json4中的元素顺序

时间:2016-05-22 02:25:48

标签: scala json4s

我在Scala中使用JSON4S以JSON格式获取我的POJO类的toString(),如下所示。

//JSON related libraries
import org.json4s.{DefaultFormats, Formats}

//JSON handling support from Scalatra
import org.scalatra.json._

// JSON library for converting the POJO toString as Json
import org.json4s.native.Json

class Customer(val id:Int, var firstName:String, var lastName:String) {

    println("Customer - Constructor  BEGIN .... ")

    def this(firstName:String, lastName:String) {
            this(Customer.inc, firstName, lastName)
    }

    //override def toString = s"Customer [Id=$id, FirstName=$firstName, LastName=$lastName]"

    override def toString = Json(DefaultFormats).write(this)

    println("Customer - Constructor END .... ")
}

但是,当我使用实例测试时,元素的顺序会失真如下。

{                                 
   "firstName": "Raghavan",
   "id": 1,                      
   "lastName": "Muthu"        
} 

我真正想要的是

{                          
   "id": 1,        
   "firstName": "Raghavan",                     
   "lastName": "Muthu"        
}           

我怎样才能做到这一点?

0 个答案:

没有答案