0

I have a json like below,

I have json like below I need to extract the value from them

{
    "filed1": "value1",
    "message": {
        "payload": [{
            "type": ["Extra","ID"],
             info": {
                "value": 8
            }
        }, {
            "type": ["Free"],
            info": {
                "value": 99
            }
        }, {
            "type": ["Actual"],
             info": {
                "value": 100
            }
        }]
    },
    "code": "0000"
}


{
    "filed1": "value1",
    "message": {
        "payload": [{
            "type": ["Extra", "new"],
            "value": 9
        }]
    },
    "code": "0001"
}

from the above two types of json .

If the input json has list of type keys then look for type field which has element Extra and get the value inside info

If the input json has one type key then check type field , if it has element Extra and get the direct va;ue

I am trying like below for type but it fails for list of types json, i.e first json input

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._

val json = parse(myjsonString, true)
val field = compact(render(json \\ "type"))

val ok = field.contains("[\"Extra\"")

if(ok == true){
println("value " +  compact(render(json \\ "value")))
}

1 Answers1

1

You need to use json4s to do the work for you. Specifically, you need to use the extract method on the json to convert it into your particular data structure. Once you have done that you can process it as Scala types.

This is my attempt at matching the structure of your JSON with Scala case classes:

case class PayloadInfo(value: Int)
case class Payload(`type`: List[String], info: PayloadInfo)
case class Message(payload: List[Payload])
case class Full(filed1: String, message: Message, code: String)

implicit val formats = DefaultFormats

val json = parse(myjsonString, true)

val full = json.extract[Full]

val res = full.message.payload.filter(_.`type`.contains("Extra"))

[ The backticks around type are required because it is a reserved word ]

I may have got the types a bit wrong but this should give you the idea of how to go about it.

You can also process the JValues directly but that is going to be much messier.

Tim
  • 26,753
  • 2
  • 16
  • 29