0

I've got a JSOn File:

JsonString="""{"schema":{"type":"struct","name":"emp_table","fields":[{"field":"emp_id","type":"string"},{"field":"emp_name","type":"String"},{"field":"city","type":"string"},{"field":"emp_sal","type":"string"},{"field":"manager_name","type":"string"},]},"payload":{"emp_id":"1","emp_name":"abc","city":"NY","emp_sal":"100000","manager_name":"xyz"}}"""

I want to parse it and get the values into an Array(1,abc,NY,100000,xyz)

I used Lift Json API in Scala:

case class Emp(val emp_id: String, val emp_name: String, val city: String, val emp_sal: String, val manager_name: String)

val stocks = ArrayBuffer[Emp]()
val json = JsonParser.parse(EmpString)

val elements = (json \\ "payload").children
for ( acct <- elements ) {
val stock = acct.extract[Emp]
stocks += stock
}
stocks.toArray
}

but its giving me as

Array[Emp] = Array(Emp(1,abc,NY,100000,xyz))

Can anyone guide me to parse this Json file maybe using any other API like GSON or jackson?

1
  • 4
    Could you clarify what your problem is exactly? From what you've explained, it looks like the JSON object is parsed correctly, given that your code explicitly ignores the schema and only takes the payload object. You can construct an array of the object fields manually afterwards, like Array(stock.emp_id, stock.emp_name, stock.city, stock.emp_sal, stock.manager_name). Commented Dec 19, 2018 at 20:31

1 Answer 1

1

If you've got an Array[Emp], and you want Array[String], you can always just flatMap() it.

empArr.flatMap(_.productIterator).map(_.toString)
//res0: Array[String] = Array(1, abc, NY, 100000, xyz)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.