how to iterate each element of json file using scala - json

JSON FILE:
need to iterate each element using scala.read the JSON file in scala and iterate over the each element & and add it the particular list.
Input:
{"details": [{"Level": "1", "member": "age", "claim": "age"}, {"Level": "2", "member": "dob", "claim": "dob"}, {"Level": "2", "member": "name", "claim": "name"}]}
output:
Memberlist=list(list(age),list(dob),list(name))
Claimlist=list(list(age),list(dob),list(name))

You can use simple and recursive path to traverse JSON objects in Scala, assuming you're using the Play Framework
val jsonDetails:JsValue = Json.parse("""
{"details":
[{"Level": "1", "member":"age", "claim":"age"},
{"Level": "2", "member": "dob", "claim": "dob2"},
{"Level": "2", "member":"name1", "claim":"name"}
]}
""")
var pathToFirstLevel = (jsonDetails\"details"\0\"Level")
var allIstancesOfMember = (jsonDetails\\"member")
Will return
res1: play.api.libs.json.JsLookupResult = JsDefined("1")
res2: Seq[play.api.libs.json.JsValue] = List("age", "dob", "name1")
You can grab the data you're looking for and populate your lists, but you'll need to convert the JsValues to values Scala can work with (use .as[T] not asInstanceOf[T])
You can also use map
var allIstancesOfMember =(jsonDetails\\"member").map(_.as[String])
There's loads of information on traversing JSON elements in Scala using the Play Framework at https://www.playframework.com/documentation/2.6.x/ScalaJson
does that answer your question?

Not sure whether this solution can fit for your requirement.
Some concrete classes used for extraction
class CC[T] { def unapply(a:Any):Option[T] = Some(a.asInstanceOf[T]) }
object M extends CC[Map[String, Any]]
object L extends CC[List[Any]]
object S extends CC[String]
ListBuffer for output.
val memberList = ListBuffer.empty[Any]
val claimList = ListBuffer.empty[Any]
for comprehension to iterate over list of details and extract each detail.
for {
Some(M(map)) <- List(JSON.parseFull(s))
L(details) = map("details")
M(language) <- details
//S(level) = language("Level") //Not so sure how to use this variable
S(member) = language("member")
S(claim) = language("claim")
} yield {
memberList += List(member) //List is used to match your output.
claimList += List(claim) //List is used to match your output.
}
Output
println(memberList)
//ListBuffer(List(m_age), List(m_dob), List(m_name))
println(claimList)
//ListBuffer(List(c_age), List(c_dob), List(c_name))
Credits to this answer

Related

Scala - how to take json as input arguments and parse it?

I am writing a small scala practice code where my input is going to be in the fashion -
{
"code": "",
"unique ID": "",
"count": "",
"names": [
{
"Matt": {
"name": "Matt",
"properties": [
"a",
"b",
"c"
],
"fav-colour": "red"
},
"jack": {
"name": "jack",
"properties": [
"a",
"b"
],
"fav-colour": "blue"
}
}
]
}
I'll be passing this file as an command line argument.
I want to know that how do I accept the input file parse the json and use the json keys in my code?
You may use a json library such as play-json to parse the json content.
You could either operate on the json AST or you could write case classes that have the same structure as your json file and let them be parsed.
You can find the documentation of the library here.
You'll first have to add playjson as depedency to your project. If you're using sbt, just add to your build.sbt file:
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.6.13"
Play json using AST
Let's read the input file:
import play.api.libs.json.Json
object Main extends App {
// first we'll need a inputstream of your json object
// this should be familiar if you know java.
val in = new FileInputStream(args(0))
// now we'll let play-json parse it
val json = Json.parse(in)
}
Let's extract some fields from the AST:
val code = (json \ "code").as[String]
val uniqueID = (json \ "unique ID").as[UUID]
for {
JsObject(nameMap) ← (json \ "names").as[Seq[JsObject]]
(name, userMeta) ← nameMap // nameMap is a Map[String, JsValue]
} println(s"User $name has the favorite color ${(userMeta \ "fav-colour").as[String]}")
Using Deserialization
As I've just described, we may create case classes that represent your structure:
case class InputFile(code: String, `unique ID`: UUID, count: String, names: Seq[Map[String, UserData]])
case class UserData(name: String, properties: Seq[String], `fav-colour`: String)
In addition you'll need to define an implicit Format e.g. in the companion object of each case class. Instead of writing it by hand you can use the Json.format macro that derives it for you:
object UserData {
implicit val format: OFormat[UserData] = Json.format[UserData]
}
object InputFile {
implicit val format: OFormat[InputFile] = Json.format[InputFile]
}
You can now deserialize your json object:
val argumentData = json.as[InputFile]
I generally prefer this approach but in your case the json structure does not fit really well. One improvement could be to add an additional getter to your InputFile class that makes accesing the fields with space and similar in the name easier:
case class InputFile(code: String, `unique ID`: UUID, count: String, names: Seq[Map[String, String]]) {
// this method is nicer to use
def uniqueId = `unique ID`
}

How to desgin a class for json when I use Gson in Kotlin?

I'm a beginner of Json and Gson, I know I can map json into a class, and map a class to json via Gson.
"My Json" is a json data, I try to design a class "My Class" to map, but I think that "My Class" is not good. Could you show me some sample code? Thanks!
My Class
data class Setting (
val _id: Long,
val Bluetooth_Stauts: Boolean,
val WiFi_Name,String
val WiFi_Statuse: Boolean
)
My Json
{
"Setting": [
{
"id": "34345",
"Bluetooth": { "Status": "ON" },
"WiFi": { "Name": "MyConnect", "Status": "OFF" }
}
,
{
"id": "16454",
"Bluetooth": { "Status": "OFF" }
}
]
}
Updated
The following is made by Rivu Chakraborty's opinion, it can work well, but it's to complex, is there a simple way?
data class BluetoothDef(val Status:Boolean=false)
data class WiFiDef(val Name:String, val Status:Boolean=false)
data class MDetail (
val _id: Long,
val bluetooth: BluetoothDef,
val wiFi:WiFiDef
)
data class MDetailsList(val mListMetail: MutableList<MDetail>)
var mBluetoothDef1=BluetoothDef()
var mWiFiDef1=WiFiDef("MyConnect 1",true)
var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)
var mBluetoothDef2=BluetoothDef(true)
var mWiFiDef2=WiFiDef("MyConnect 2")
var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)
val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)
var aMDetailsList=MDetailsList(mListMetail)
val json = Gson().toJson(aMDetailsList)
As per your JSON Structure, I think below class definition should work with Gson
data class Setting (
val id: Long,
val Bluetooth: BluetoothDef,
val WiFi:WiFiDef
)
data class BluetoothDef(val Status:String)
data class WiFiDef(val Name:String, val Status:String)
Explanation -
If you're getting an object in your JSON, you should define a class for that to use with Gson.
Data types should match, use String if you're getting Strings like "ON" and "OFF". You can use Boolean if you're getting true and false (without quotes).
The JSON Element name should match the variable/property name unless you're using #SerializedName to define JSON variable name while using different variable/property name.
*Note You can rename the classes if you want
I think it'll be helpful for you

How to get json parent property instead of taken all of same property name in json4s

I use json4s and scala 2.11.12
the exmaple json is:
{ "name": "joe",
"children": [
{
"name": "Mary",
"age": 5
},
{
"name": "Mazy",
"age": 3
}
]
}
when I want to get the name, instead of get parent name "joe", it give me all names of parents and child by(I use json4s library http://json4s.org/)
compact(render(json \\ "name"))
it return me :
res2: String = {"name":"joe","name":"Mary","name":"Mazy"}
I only need {"name":"joe"}
I only need parent name, How to get only parent name?
val json = "..."
import org.json4s._
import org.json4s.native.JsonMethods._
val parent: JValue = json \ "name"
The \ method which with the native implementation of JSON4S will be lift-json based, will look up a field value by name inside a JSON object. Note, your json needs to be a JValue before you can do this, so from a val jsonData: String you need to call val json = Json.parse(jsonData) to get the initial JValue.
The double backslash \\ method will find all children of the JSON that have a given property, so that's why you are getting the entire set of JObject matches back.

How to add "data" and "paging" section on JSON marshalling

I know i can customize the JSON response registering JSON marshallers to Domain entities, even i can create profiles with names for different responses.
This is done filling an array that later will be marshalled like:
JSON.registerObjectMarshaller(myDomain) {
def returnArray = [:]
returnArray['id'] = it.id
returnArray['name'] = it.name
returnArray['price'] = it.price
return returnArray
}
What i want is to alter the way it gets marshalled to have two sections like
{
"paging": {
"total": 100
},
"data": [
{
"id": 1,
"description": "description 1",
}
},
...
]
}
I assume i have to implemetn a custom JSON Marshaller but i don't know how to use it for a specific response instead of wide application.
EDIT: I assume i'll need a custom RENDERER apart from the marshaller. Is this one that i don't know how to use for specific response.
What about a simple:
def json = new JSON([ paging: [ total: myArray.totalCount ], data: myArray ])
Your domain objects will be converted with the marshaller you have set up while your paging data will simply be transformed into JSON.

Serializing a Scala List to JSON in Play2

I am trying to deserialize a list of Scala objects to a JSON map in Play2 - a pretty trivial use case with JSON, I'd say. My JSON output would be something along the lines of:
{
"users": [
{
"name": "Example 1",
"age": 20
},
{
"name": "Example 2",
"age": 42
}
]
}
To achieve this I am looking at the Play2's JSON documentation titled "The Play JSON library". To me their examples are pretty trivial, and I've confirmed that they work for me. Hence, I am able to deserialize a single User object properly.
But making a map containing a list in JSON seems a bit verbose in Play2, when I read the documentation. Is there something I am not grokking?
This is basically my simple Scala code:
case class User(name: String, age: Int)
object UserList {
implicit val userFormat = Json.format[User]
val userList = List(User("Example 1", 20), User("Example 2", 42))
val oneUser = Json.toJson(userList(0)) // Deserialize one Scala object properly to JSON.
// JSON: { "user" : [ <-- put content of userList here. How?
// ]
// }
}
So my question would be; how can I transform the content of the userList List above to a hash in the JSON in a more generic way than explicitly writing out each hash element, as the Play documentation suggests?
scala> import play.api.libs.json._
import play.api.libs.json._
scala> case class User(name: String, age: Int)
defined class User
scala> implicit val userFormat = Json.format[User]
userFormat: play.api.libs.json.OFormat[User] = play.api.libs.json.OFormat$$anon$1#38d2c662
scala> val userList = List(User("Example 1", 20), User("Example 2", 42))
userList: List[User] = List(User(Example 1,20), User(Example 2,42))
scala> val users = Json.obj("users" -> userList)
users: play.api.libs.json.JsObject = {"users":[{"name":"Example 1","age":20},{"name":"Example 2","age":42}]}