How to validate list body in JavalinHow to use Jackson to deserialise an array of objectsValidate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScriptHow do I efficiently iterate over each entry in a Java Map?A comprehensive regex for phone number validation(Built-in) way in JavaScript to check if a string is a valid numberHow to validate an email address using a regular expression?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?

Why are Tucker and Malcolm not dead?

Are employers legally allowed to pay employees in goods and services equal to or greater than the minimum wage?

Solution to German Tank Problem

These were just lying around

Random Double Arc Endpoint Angles

If clocks themselves are based on light signals, wouldn't we expect the measured speed of light to always be the same constant?

Why are Gatwick's runways too close together?

0xF1 opcode-prefix on i80286

How does proof assistant organize knowledge?

how do companies get money from being listed publicly

Heat equation: Squiggly lines

visible indication that a cell is not evaluatable

How much maintenance time did it take to make an F4U Corsair ready for another flight?

Is this n-speak?

Markov-chain sentence generator in Python

Is 悪いところを見つかった proper Japanese?

Do I have to cite common CS algorithms?

Why did I get only 5 points even though I won?

Generate Brainfuck for the numbers 1–255

Super Duper Vdd stiffening required on 555 timer, what is the best way?

How can this older-style irrigation tee be replaced?

Understanding this peak detector circuit

A continuous water "planet" ring around a star

How to assign many blockers at the same time?



How to validate list body in Javalin


How to use Jackson to deserialise an array of objectsValidate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScriptHow do I efficiently iterate over each entry in a Java Map?A comprehensive regex for phone number validation(Built-in) way in JavaScript to check if a string is a valid numberHow to validate an email address using a regular expression?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















My DELETE request accepts a list of Items that should be deleted.



I want to validate that the request body is a valid list of Item objects.



The example given in the Javalin docs doesn't mention lists.



In order to get the code to compile, I had to do this:



 TypedValidator<List> requestValidator = ctx.validatedBodyAsClass(List.class);
List<Item> items = requestValidator.getOrThrow();
logger.info("Received delete request for ", Arrays.toString(items.toArray()));
logger.info("items is type ", items.getClass());
for (Item item : items)
logger.info("Deleting ", item.name);



The validation passes and the ctx body is printed correctly in the following line.
The problem is, there is an unchecked assignment at getOrThrow() and indeed the loop doesn't work:



[qtp1679441380-34] INFO com.myorg.MyClass - Received delete request for [name=FooName, type=BarType]
[qtp1679441380-34] INFO com.ericsson.cdzm.ws.controllers.ScheduleController - items is type class java.util.ArrayList
[qtp1679441380-34] WARN io.javalin.core.ExceptionMapper - Uncaught exception
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.myorg.Item
at com.myorg.MyClass.deleteItems(MyClass.java:51)


Edit: The java.util.LinkedHashMap seems to be because actually, items is of type ArrayList<LinkedHashMap<String,String>>. In other words, Javalin didn't parse or validate the body contents at all! It only converted the Json name=value mappings into a Java Map.



What would be a better way to validate the incoming Json and parse it to a list of Items?



I've tested on Javalin 2.6.0 and 2.8.0.










share|improve this question
































    0















    My DELETE request accepts a list of Items that should be deleted.



    I want to validate that the request body is a valid list of Item objects.



    The example given in the Javalin docs doesn't mention lists.



    In order to get the code to compile, I had to do this:



     TypedValidator<List> requestValidator = ctx.validatedBodyAsClass(List.class);
    List<Item> items = requestValidator.getOrThrow();
    logger.info("Received delete request for ", Arrays.toString(items.toArray()));
    logger.info("items is type ", items.getClass());
    for (Item item : items)
    logger.info("Deleting ", item.name);



    The validation passes and the ctx body is printed correctly in the following line.
    The problem is, there is an unchecked assignment at getOrThrow() and indeed the loop doesn't work:



    [qtp1679441380-34] INFO com.myorg.MyClass - Received delete request for [name=FooName, type=BarType]
    [qtp1679441380-34] INFO com.ericsson.cdzm.ws.controllers.ScheduleController - items is type class java.util.ArrayList
    [qtp1679441380-34] WARN io.javalin.core.ExceptionMapper - Uncaught exception
    java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.myorg.Item
    at com.myorg.MyClass.deleteItems(MyClass.java:51)


    Edit: The java.util.LinkedHashMap seems to be because actually, items is of type ArrayList<LinkedHashMap<String,String>>. In other words, Javalin didn't parse or validate the body contents at all! It only converted the Json name=value mappings into a Java Map.



    What would be a better way to validate the incoming Json and parse it to a list of Items?



    I've tested on Javalin 2.6.0 and 2.8.0.










    share|improve this question




























      0












      0








      0








      My DELETE request accepts a list of Items that should be deleted.



      I want to validate that the request body is a valid list of Item objects.



      The example given in the Javalin docs doesn't mention lists.



      In order to get the code to compile, I had to do this:



       TypedValidator<List> requestValidator = ctx.validatedBodyAsClass(List.class);
      List<Item> items = requestValidator.getOrThrow();
      logger.info("Received delete request for ", Arrays.toString(items.toArray()));
      logger.info("items is type ", items.getClass());
      for (Item item : items)
      logger.info("Deleting ", item.name);



      The validation passes and the ctx body is printed correctly in the following line.
      The problem is, there is an unchecked assignment at getOrThrow() and indeed the loop doesn't work:



      [qtp1679441380-34] INFO com.myorg.MyClass - Received delete request for [name=FooName, type=BarType]
      [qtp1679441380-34] INFO com.ericsson.cdzm.ws.controllers.ScheduleController - items is type class java.util.ArrayList
      [qtp1679441380-34] WARN io.javalin.core.ExceptionMapper - Uncaught exception
      java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.myorg.Item
      at com.myorg.MyClass.deleteItems(MyClass.java:51)


      Edit: The java.util.LinkedHashMap seems to be because actually, items is of type ArrayList<LinkedHashMap<String,String>>. In other words, Javalin didn't parse or validate the body contents at all! It only converted the Json name=value mappings into a Java Map.



      What would be a better way to validate the incoming Json and parse it to a list of Items?



      I've tested on Javalin 2.6.0 and 2.8.0.










      share|improve this question
















      My DELETE request accepts a list of Items that should be deleted.



      I want to validate that the request body is a valid list of Item objects.



      The example given in the Javalin docs doesn't mention lists.



      In order to get the code to compile, I had to do this:



       TypedValidator<List> requestValidator = ctx.validatedBodyAsClass(List.class);
      List<Item> items = requestValidator.getOrThrow();
      logger.info("Received delete request for ", Arrays.toString(items.toArray()));
      logger.info("items is type ", items.getClass());
      for (Item item : items)
      logger.info("Deleting ", item.name);



      The validation passes and the ctx body is printed correctly in the following line.
      The problem is, there is an unchecked assignment at getOrThrow() and indeed the loop doesn't work:



      [qtp1679441380-34] INFO com.myorg.MyClass - Received delete request for [name=FooName, type=BarType]
      [qtp1679441380-34] INFO com.ericsson.cdzm.ws.controllers.ScheduleController - items is type class java.util.ArrayList
      [qtp1679441380-34] WARN io.javalin.core.ExceptionMapper - Uncaught exception
      java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.myorg.Item
      at com.myorg.MyClass.deleteItems(MyClass.java:51)


      Edit: The java.util.LinkedHashMap seems to be because actually, items is of type ArrayList<LinkedHashMap<String,String>>. In other words, Javalin didn't parse or validate the body contents at all! It only converted the Json name=value mappings into a Java Map.



      What would be a better way to validate the incoming Json and parse it to a list of Items?



      I've tested on Javalin 2.6.0 and 2.8.0.







      java validation javalin






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 12:03







      Jolta

















      asked Mar 27 at 9:22









      JoltaJolta

      2,4061 gold badge23 silver badges39 bronze badges




      2,4061 gold badge23 silver badges39 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0














          What I had missed, and can't find in the Javalin docs, was that I have to use array types rather than parameterized Collection types. This works:



           TypedValidator<Item[]> requestValidator = ctx.bodyValidator(Item[].class);
          List<Item> items = Arrays.asList(requestValidator.get());


          Still, would love to know why this is - I suspect it is related to Java's type system somehow?



          I could also directly access the Jackson ObjectMapper object and use it like you would use Jackson. The drawback is that I don't benefit from Javalin's automatic throwing of BadRequestResponse etc. I think using array types is a small price to pay for this.



           try 
          List<ScheduleRequest> items = JavalinJackson.getObjectMapper().readValue(ctx.body(), new TypeReference<List<ScheduleRequest>>());
          catch (IOException e)
          throw new BadRequestResponse(e.getMessage());






          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%2f55373642%2fhow-to-validate-list-body-in-javalin%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            What I had missed, and can't find in the Javalin docs, was that I have to use array types rather than parameterized Collection types. This works:



             TypedValidator<Item[]> requestValidator = ctx.bodyValidator(Item[].class);
            List<Item> items = Arrays.asList(requestValidator.get());


            Still, would love to know why this is - I suspect it is related to Java's type system somehow?



            I could also directly access the Jackson ObjectMapper object and use it like you would use Jackson. The drawback is that I don't benefit from Javalin's automatic throwing of BadRequestResponse etc. I think using array types is a small price to pay for this.



             try 
            List<ScheduleRequest> items = JavalinJackson.getObjectMapper().readValue(ctx.body(), new TypeReference<List<ScheduleRequest>>());
            catch (IOException e)
            throw new BadRequestResponse(e.getMessage());






            share|improve this answer































              0














              What I had missed, and can't find in the Javalin docs, was that I have to use array types rather than parameterized Collection types. This works:



               TypedValidator<Item[]> requestValidator = ctx.bodyValidator(Item[].class);
              List<Item> items = Arrays.asList(requestValidator.get());


              Still, would love to know why this is - I suspect it is related to Java's type system somehow?



              I could also directly access the Jackson ObjectMapper object and use it like you would use Jackson. The drawback is that I don't benefit from Javalin's automatic throwing of BadRequestResponse etc. I think using array types is a small price to pay for this.



               try 
              List<ScheduleRequest> items = JavalinJackson.getObjectMapper().readValue(ctx.body(), new TypeReference<List<ScheduleRequest>>());
              catch (IOException e)
              throw new BadRequestResponse(e.getMessage());






              share|improve this answer





























                0












                0








                0







                What I had missed, and can't find in the Javalin docs, was that I have to use array types rather than parameterized Collection types. This works:



                 TypedValidator<Item[]> requestValidator = ctx.bodyValidator(Item[].class);
                List<Item> items = Arrays.asList(requestValidator.get());


                Still, would love to know why this is - I suspect it is related to Java's type system somehow?



                I could also directly access the Jackson ObjectMapper object and use it like you would use Jackson. The drawback is that I don't benefit from Javalin's automatic throwing of BadRequestResponse etc. I think using array types is a small price to pay for this.



                 try 
                List<ScheduleRequest> items = JavalinJackson.getObjectMapper().readValue(ctx.body(), new TypeReference<List<ScheduleRequest>>());
                catch (IOException e)
                throw new BadRequestResponse(e.getMessage());






                share|improve this answer















                What I had missed, and can't find in the Javalin docs, was that I have to use array types rather than parameterized Collection types. This works:



                 TypedValidator<Item[]> requestValidator = ctx.bodyValidator(Item[].class);
                List<Item> items = Arrays.asList(requestValidator.get());


                Still, would love to know why this is - I suspect it is related to Java's type system somehow?



                I could also directly access the Jackson ObjectMapper object and use it like you would use Jackson. The drawback is that I don't benefit from Javalin's automatic throwing of BadRequestResponse etc. I think using array types is a small price to pay for this.



                 try 
                List<ScheduleRequest> items = JavalinJackson.getObjectMapper().readValue(ctx.body(), new TypeReference<List<ScheduleRequest>>());
                catch (IOException e)
                throw new BadRequestResponse(e.getMessage());







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 27 at 12:37

























                answered Mar 27 at 11:53









                JoltaJolta

                2,4061 gold badge23 silver badges39 bronze badges




                2,4061 gold badge23 silver badges39 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55373642%2fhow-to-validate-list-body-in-javalin%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현