Scala play JSON, lookup and match defined field holding null value












0














I have the following Json block that I have returned as a JsObject



{
"first_block": [
{
"name": "demo",
"description": "first demo description"
}
],
"second_block": [
{
"name": "second_demo",
"description": "second demo description",
"nested_second": [
{
"name": "bob",
"value": null
},
{
"name": "john",
"value": null
}
]
}
]
}


From this, I want to return a list of all the possible values I could have in the second block, nested array for name and value. so with the example above
List([bob,null],[john,null]) or something along those lines.



The issue I am having is with the value section understanding null values. I've tried to match against it and return a string "null" but I can't get it to match on Null values.



What would be the best way for me to return back the name and values in the nested_second array.



I've tried using case classes and readAsNullable with no luck, and my latest attempt has gone along these lines:



val secondBlock = (jsObj  "second_block").as[List[JsValue]]

secondBlock.foreach(nested_block => {
val nestedBlock = (nested_block "nested_second").as[List[JsValue]]
nestedBlock.foreach(value => {
val name = (value "name").as[String] //always a string
var convertedValue = ""
val replacement_value = value "value"
replacement_value match {
case JsDefined(null) => convertedValue = "null"
case _ => convertedValue = replacement_value.as[String]
}

println(name)
println(convertedValue)
})
}
)


It seems convertedValue returns as 'JsDefined(null)' regardless and I'm sure the way I'm doing it is horrifically bad.










share|improve this question





























    0














    I have the following Json block that I have returned as a JsObject



    {
    "first_block": [
    {
    "name": "demo",
    "description": "first demo description"
    }
    ],
    "second_block": [
    {
    "name": "second_demo",
    "description": "second demo description",
    "nested_second": [
    {
    "name": "bob",
    "value": null
    },
    {
    "name": "john",
    "value": null
    }
    ]
    }
    ]
    }


    From this, I want to return a list of all the possible values I could have in the second block, nested array for name and value. so with the example above
    List([bob,null],[john,null]) or something along those lines.



    The issue I am having is with the value section understanding null values. I've tried to match against it and return a string "null" but I can't get it to match on Null values.



    What would be the best way for me to return back the name and values in the nested_second array.



    I've tried using case classes and readAsNullable with no luck, and my latest attempt has gone along these lines:



    val secondBlock = (jsObj  "second_block").as[List[JsValue]]

    secondBlock.foreach(nested_block => {
    val nestedBlock = (nested_block "nested_second").as[List[JsValue]]
    nestedBlock.foreach(value => {
    val name = (value "name").as[String] //always a string
    var convertedValue = ""
    val replacement_value = value "value"
    replacement_value match {
    case JsDefined(null) => convertedValue = "null"
    case _ => convertedValue = replacement_value.as[String]
    }

    println(name)
    println(convertedValue)
    })
    }
    )


    It seems convertedValue returns as 'JsDefined(null)' regardless and I'm sure the way I'm doing it is horrifically bad.










    share|improve this question



























      0












      0








      0







      I have the following Json block that I have returned as a JsObject



      {
      "first_block": [
      {
      "name": "demo",
      "description": "first demo description"
      }
      ],
      "second_block": [
      {
      "name": "second_demo",
      "description": "second demo description",
      "nested_second": [
      {
      "name": "bob",
      "value": null
      },
      {
      "name": "john",
      "value": null
      }
      ]
      }
      ]
      }


      From this, I want to return a list of all the possible values I could have in the second block, nested array for name and value. so with the example above
      List([bob,null],[john,null]) or something along those lines.



      The issue I am having is with the value section understanding null values. I've tried to match against it and return a string "null" but I can't get it to match on Null values.



      What would be the best way for me to return back the name and values in the nested_second array.



      I've tried using case classes and readAsNullable with no luck, and my latest attempt has gone along these lines:



      val secondBlock = (jsObj  "second_block").as[List[JsValue]]

      secondBlock.foreach(nested_block => {
      val nestedBlock = (nested_block "nested_second").as[List[JsValue]]
      nestedBlock.foreach(value => {
      val name = (value "name").as[String] //always a string
      var convertedValue = ""
      val replacement_value = value "value"
      replacement_value match {
      case JsDefined(null) => convertedValue = "null"
      case _ => convertedValue = replacement_value.as[String]
      }

      println(name)
      println(convertedValue)
      })
      }
      )


      It seems convertedValue returns as 'JsDefined(null)' regardless and I'm sure the way I'm doing it is horrifically bad.










      share|improve this question















      I have the following Json block that I have returned as a JsObject



      {
      "first_block": [
      {
      "name": "demo",
      "description": "first demo description"
      }
      ],
      "second_block": [
      {
      "name": "second_demo",
      "description": "second demo description",
      "nested_second": [
      {
      "name": "bob",
      "value": null
      },
      {
      "name": "john",
      "value": null
      }
      ]
      }
      ]
      }


      From this, I want to return a list of all the possible values I could have in the second block, nested array for name and value. so with the example above
      List([bob,null],[john,null]) or something along those lines.



      The issue I am having is with the value section understanding null values. I've tried to match against it and return a string "null" but I can't get it to match on Null values.



      What would be the best way for me to return back the name and values in the nested_second array.



      I've tried using case classes and readAsNullable with no luck, and my latest attempt has gone along these lines:



      val secondBlock = (jsObj  "second_block").as[List[JsValue]]

      secondBlock.foreach(nested_block => {
      val nestedBlock = (nested_block "nested_second").as[List[JsValue]]
      nestedBlock.foreach(value => {
      val name = (value "name").as[String] //always a string
      var convertedValue = ""
      val replacement_value = value "value"
      replacement_value match {
      case JsDefined(null) => convertedValue = "null"
      case _ => convertedValue = replacement_value.as[String]
      }

      println(name)
      println(convertedValue)
      })
      }
      )


      It seems convertedValue returns as 'JsDefined(null)' regardless and I'm sure the way I'm doing it is horrifically bad.







      json scala playframework play-json






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 24 '18 at 13:08









      ygor

      1,086614




      1,086614










      asked Nov 23 '18 at 12:05









      Curious_BopCurious_Bop

      961616




      961616
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Replace JsDefined(null) with JsDefined(JsNull).



          You probably got confused, because println(JsDefined(JsNull)) prints as JsDefined(null). But that is not, how null value of a JSON field is represented. null is represented as case object JsNull. This is just a good API design, where possible cases are represented with a hierarchy of classes:



          enter image description here






          share|improve this answer























          • perfect thanks for that extra bit of detail
            – Curious_Bop
            Nov 23 '18 at 13:49



















          0














          With play-json I use always case-classes!



          I simplified your problem to the essence:



          import play.api.libs.json._

          val jsonStr = """[
          {
          "name": "bob",
          "value": null
          },
          {
          "name": "john",
          "value": "aValue"
          },
          {
          "name": "john",
          "value": null
          }
          ]"""


          Define a case class



          case class Element(name: String, value: Option[String])


          Add a formatter in the companion object:



          object Element {
          implicit val jsonFormat: Format[Element] = Json.format[Element]
          }


          An use validate:



          Json.parse(jsonStr).validate[Seq[Element]] match {
          case JsSuccess(elems, _) => println(elems)
          case other => println(s"Handle exception $other")
          }


          This returns: List(Element(bob,None), Element(john,Some(aValue)), Element(john,None))



          Now you can do whatever you want with the values.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53446417%2fscala-play-json-lookup-and-match-defined-field-holding-null-value%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Replace JsDefined(null) with JsDefined(JsNull).



            You probably got confused, because println(JsDefined(JsNull)) prints as JsDefined(null). But that is not, how null value of a JSON field is represented. null is represented as case object JsNull. This is just a good API design, where possible cases are represented with a hierarchy of classes:



            enter image description here






            share|improve this answer























            • perfect thanks for that extra bit of detail
              – Curious_Bop
              Nov 23 '18 at 13:49
















            0














            Replace JsDefined(null) with JsDefined(JsNull).



            You probably got confused, because println(JsDefined(JsNull)) prints as JsDefined(null). But that is not, how null value of a JSON field is represented. null is represented as case object JsNull. This is just a good API design, where possible cases are represented with a hierarchy of classes:



            enter image description here






            share|improve this answer























            • perfect thanks for that extra bit of detail
              – Curious_Bop
              Nov 23 '18 at 13:49














            0












            0








            0






            Replace JsDefined(null) with JsDefined(JsNull).



            You probably got confused, because println(JsDefined(JsNull)) prints as JsDefined(null). But that is not, how null value of a JSON field is represented. null is represented as case object JsNull. This is just a good API design, where possible cases are represented with a hierarchy of classes:



            enter image description here






            share|improve this answer














            Replace JsDefined(null) with JsDefined(JsNull).



            You probably got confused, because println(JsDefined(JsNull)) prints as JsDefined(null). But that is not, how null value of a JSON field is represented. null is represented as case object JsNull. This is just a good API design, where possible cases are represented with a hierarchy of classes:



            enter image description here







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '18 at 13:20

























            answered Nov 23 '18 at 12:56









            ygorygor

            1,086614




            1,086614












            • perfect thanks for that extra bit of detail
              – Curious_Bop
              Nov 23 '18 at 13:49


















            • perfect thanks for that extra bit of detail
              – Curious_Bop
              Nov 23 '18 at 13:49
















            perfect thanks for that extra bit of detail
            – Curious_Bop
            Nov 23 '18 at 13:49




            perfect thanks for that extra bit of detail
            – Curious_Bop
            Nov 23 '18 at 13:49













            0














            With play-json I use always case-classes!



            I simplified your problem to the essence:



            import play.api.libs.json._

            val jsonStr = """[
            {
            "name": "bob",
            "value": null
            },
            {
            "name": "john",
            "value": "aValue"
            },
            {
            "name": "john",
            "value": null
            }
            ]"""


            Define a case class



            case class Element(name: String, value: Option[String])


            Add a formatter in the companion object:



            object Element {
            implicit val jsonFormat: Format[Element] = Json.format[Element]
            }


            An use validate:



            Json.parse(jsonStr).validate[Seq[Element]] match {
            case JsSuccess(elems, _) => println(elems)
            case other => println(s"Handle exception $other")
            }


            This returns: List(Element(bob,None), Element(john,Some(aValue)), Element(john,None))



            Now you can do whatever you want with the values.






            share|improve this answer


























              0














              With play-json I use always case-classes!



              I simplified your problem to the essence:



              import play.api.libs.json._

              val jsonStr = """[
              {
              "name": "bob",
              "value": null
              },
              {
              "name": "john",
              "value": "aValue"
              },
              {
              "name": "john",
              "value": null
              }
              ]"""


              Define a case class



              case class Element(name: String, value: Option[String])


              Add a formatter in the companion object:



              object Element {
              implicit val jsonFormat: Format[Element] = Json.format[Element]
              }


              An use validate:



              Json.parse(jsonStr).validate[Seq[Element]] match {
              case JsSuccess(elems, _) => println(elems)
              case other => println(s"Handle exception $other")
              }


              This returns: List(Element(bob,None), Element(john,Some(aValue)), Element(john,None))



              Now you can do whatever you want with the values.






              share|improve this answer
























                0












                0








                0






                With play-json I use always case-classes!



                I simplified your problem to the essence:



                import play.api.libs.json._

                val jsonStr = """[
                {
                "name": "bob",
                "value": null
                },
                {
                "name": "john",
                "value": "aValue"
                },
                {
                "name": "john",
                "value": null
                }
                ]"""


                Define a case class



                case class Element(name: String, value: Option[String])


                Add a formatter in the companion object:



                object Element {
                implicit val jsonFormat: Format[Element] = Json.format[Element]
                }


                An use validate:



                Json.parse(jsonStr).validate[Seq[Element]] match {
                case JsSuccess(elems, _) => println(elems)
                case other => println(s"Handle exception $other")
                }


                This returns: List(Element(bob,None), Element(john,Some(aValue)), Element(john,None))



                Now you can do whatever you want with the values.






                share|improve this answer












                With play-json I use always case-classes!



                I simplified your problem to the essence:



                import play.api.libs.json._

                val jsonStr = """[
                {
                "name": "bob",
                "value": null
                },
                {
                "name": "john",
                "value": "aValue"
                },
                {
                "name": "john",
                "value": null
                }
                ]"""


                Define a case class



                case class Element(name: String, value: Option[String])


                Add a formatter in the companion object:



                object Element {
                implicit val jsonFormat: Format[Element] = Json.format[Element]
                }


                An use validate:



                Json.parse(jsonStr).validate[Seq[Element]] match {
                case JsSuccess(elems, _) => println(elems)
                case other => println(s"Handle exception $other")
                }


                This returns: List(Element(bob,None), Element(john,Some(aValue)), Element(john,None))



                Now you can do whatever you want with the values.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 13:02









                pmepme

                2,36111124




                2,36111124






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53446417%2fscala-play-json-lookup-and-match-defined-field-holding-null-value%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    What visual should I use to simply compare current year value vs last year in Power BI desktop

                    Alexandru Averescu

                    Trompette piccolo