2

I am using JSON4S in Scala to get the toString() of my POJO class in JSON format as follows.

//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 .... ")
}

However when I test this with an instance, the order of elements is distorted as follows.

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

What I really want is

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

How can I achieve this?

itsraghz
  • 857
  • 1
  • 11
  • 25
  • 1
    Why would you want this? http://stackoverflow.com/questions/3948206/json-order-mixed-up – ars May 22 '16 at 09:03
  • @ars, I think and feel it would be more appropriate and sensible if Id comes first and both the names are together in the JSON output. – itsraghz May 22 '16 at 09:35
  • 3
    See the the question I've attached. "A (JSON) object is an unordered set of name/value pairs" -- it is a quote from the JSON specification. – ars May 22 '16 at 09:39
  • @ars, thanks. I got that. I was just thinking is there a simple way to do it in JSON4S like how we used to do in GSON with a LinkedHashMap. – itsraghz May 23 '16 at 05:24

0 Answers0