How can I parse a JSON object with an empty value in Java?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm building a test suite to test my Vert.x API that implements a couple of sorting algorithms. One of the test cases that I'd like to cover is to handle null or empty values in the unsorted array:



The request body is a JSON string that I create like this:



final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";



Currently I'm parsing the JSON in the request handler using Vert.x JsonObject and JsonArray.



import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;

private void doBubbleSort(RoutingContext routingContext) {

JsonObject json = routingContext.getBodyAsJson();
JsonArray jsonArray = json.getJsonArray("arr");

....

}


This is the error I'm getting



    SEVERE: Unexpected exception in route
io.vertx.core.json.DecodeException: Failed to decode:Unexpected character (',' (code 44)): expected a value
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 49]
at io.vertx.core.json.Json.decodeValue(Json.java:172)
at io.vertx.core.json.JsonObject.fromBuffer(JsonObject.java:960)
at io.vertx.core.json.JsonObject.<init>(JsonObject.java:73)
at io.vertx.ext.web.impl.RoutingContextImpl.getBodyAsJson(RoutingContextImpl.java:263)
at io.vertx.ext.web.impl.RoutingContextDecorator.getBodyAsJson(RoutingContextDecorator.java:123)
at za.co.offerzen.SortVerticle.doBubbleSort(SortVerticle.java:80)
at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:272)
at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)


How can I parse the request when there is an empty value in the json? Ideally, I only want all the int values from the request body and ignore or strip out empty, null or missing values. Do I need to iterate over the request body before parsing it to json, and check whether each value instanceof int? Or is there another way?



Apart from JsonObject and JsonArray, I can get the request body as a Buffer or as a String



Thanks.










share|improve this question























  • This json should actually run into an exception/error. This is just not correct json and it's no wonder that it will cause a parser to fail.

    – maio290
    Jan 3 at 11:22











  • @maio290 okay. that's not really helpful. I'm trying to create a json request with an empty/missing value. So I'm also not surprised that it fails, but I'm looking for another solution, like doing something before parsing.

    – krankit
    Jan 3 at 11:40











  • You cannot use routingContext.getBodyAsJson(); if its not a valid json this will throw an exception. Use routingContext.getBodyAsString() and parse that string as you wish.

    – taygetos
    Jan 5 at 13:41


















0















I'm building a test suite to test my Vert.x API that implements a couple of sorting algorithms. One of the test cases that I'd like to cover is to handle null or empty values in the unsorted array:



The request body is a JSON string that I create like this:



final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";



Currently I'm parsing the JSON in the request handler using Vert.x JsonObject and JsonArray.



import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;

private void doBubbleSort(RoutingContext routingContext) {

JsonObject json = routingContext.getBodyAsJson();
JsonArray jsonArray = json.getJsonArray("arr");

....

}


This is the error I'm getting



    SEVERE: Unexpected exception in route
io.vertx.core.json.DecodeException: Failed to decode:Unexpected character (',' (code 44)): expected a value
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 49]
at io.vertx.core.json.Json.decodeValue(Json.java:172)
at io.vertx.core.json.JsonObject.fromBuffer(JsonObject.java:960)
at io.vertx.core.json.JsonObject.<init>(JsonObject.java:73)
at io.vertx.ext.web.impl.RoutingContextImpl.getBodyAsJson(RoutingContextImpl.java:263)
at io.vertx.ext.web.impl.RoutingContextDecorator.getBodyAsJson(RoutingContextDecorator.java:123)
at za.co.offerzen.SortVerticle.doBubbleSort(SortVerticle.java:80)
at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:272)
at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)


How can I parse the request when there is an empty value in the json? Ideally, I only want all the int values from the request body and ignore or strip out empty, null or missing values. Do I need to iterate over the request body before parsing it to json, and check whether each value instanceof int? Or is there another way?



Apart from JsonObject and JsonArray, I can get the request body as a Buffer or as a String



Thanks.










share|improve this question























  • This json should actually run into an exception/error. This is just not correct json and it's no wonder that it will cause a parser to fail.

    – maio290
    Jan 3 at 11:22











  • @maio290 okay. that's not really helpful. I'm trying to create a json request with an empty/missing value. So I'm also not surprised that it fails, but I'm looking for another solution, like doing something before parsing.

    – krankit
    Jan 3 at 11:40











  • You cannot use routingContext.getBodyAsJson(); if its not a valid json this will throw an exception. Use routingContext.getBodyAsString() and parse that string as you wish.

    – taygetos
    Jan 5 at 13:41














0












0








0








I'm building a test suite to test my Vert.x API that implements a couple of sorting algorithms. One of the test cases that I'd like to cover is to handle null or empty values in the unsorted array:



The request body is a JSON string that I create like this:



final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";



Currently I'm parsing the JSON in the request handler using Vert.x JsonObject and JsonArray.



import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;

private void doBubbleSort(RoutingContext routingContext) {

JsonObject json = routingContext.getBodyAsJson();
JsonArray jsonArray = json.getJsonArray("arr");

....

}


This is the error I'm getting



    SEVERE: Unexpected exception in route
io.vertx.core.json.DecodeException: Failed to decode:Unexpected character (',' (code 44)): expected a value
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 49]
at io.vertx.core.json.Json.decodeValue(Json.java:172)
at io.vertx.core.json.JsonObject.fromBuffer(JsonObject.java:960)
at io.vertx.core.json.JsonObject.<init>(JsonObject.java:73)
at io.vertx.ext.web.impl.RoutingContextImpl.getBodyAsJson(RoutingContextImpl.java:263)
at io.vertx.ext.web.impl.RoutingContextDecorator.getBodyAsJson(RoutingContextDecorator.java:123)
at za.co.offerzen.SortVerticle.doBubbleSort(SortVerticle.java:80)
at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:272)
at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)


How can I parse the request when there is an empty value in the json? Ideally, I only want all the int values from the request body and ignore or strip out empty, null or missing values. Do I need to iterate over the request body before parsing it to json, and check whether each value instanceof int? Or is there another way?



Apart from JsonObject and JsonArray, I can get the request body as a Buffer or as a String



Thanks.










share|improve this question














I'm building a test suite to test my Vert.x API that implements a couple of sorting algorithms. One of the test cases that I'd like to cover is to handle null or empty values in the unsorted array:



The request body is a JSON string that I create like this:



final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";



Currently I'm parsing the JSON in the request handler using Vert.x JsonObject and JsonArray.



import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;

private void doBubbleSort(RoutingContext routingContext) {

JsonObject json = routingContext.getBodyAsJson();
JsonArray jsonArray = json.getJsonArray("arr");

....

}


This is the error I'm getting



    SEVERE: Unexpected exception in route
io.vertx.core.json.DecodeException: Failed to decode:Unexpected character (',' (code 44)): expected a value
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 49]
at io.vertx.core.json.Json.decodeValue(Json.java:172)
at io.vertx.core.json.JsonObject.fromBuffer(JsonObject.java:960)
at io.vertx.core.json.JsonObject.<init>(JsonObject.java:73)
at io.vertx.ext.web.impl.RoutingContextImpl.getBodyAsJson(RoutingContextImpl.java:263)
at io.vertx.ext.web.impl.RoutingContextDecorator.getBodyAsJson(RoutingContextDecorator.java:123)
at za.co.offerzen.SortVerticle.doBubbleSort(SortVerticle.java:80)
at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:272)
at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)


How can I parse the request when there is an empty value in the json? Ideally, I only want all the int values from the request body and ignore or strip out empty, null or missing values. Do I need to iterate over the request body before parsing it to json, and check whether each value instanceof int? Or is there another way?



Apart from JsonObject and JsonArray, I can get the request body as a Buffer or as a String



Thanks.







json java-8 null vert.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 3 at 11:11









krankitkrankit

2217




2217













  • This json should actually run into an exception/error. This is just not correct json and it's no wonder that it will cause a parser to fail.

    – maio290
    Jan 3 at 11:22











  • @maio290 okay. that's not really helpful. I'm trying to create a json request with an empty/missing value. So I'm also not surprised that it fails, but I'm looking for another solution, like doing something before parsing.

    – krankit
    Jan 3 at 11:40











  • You cannot use routingContext.getBodyAsJson(); if its not a valid json this will throw an exception. Use routingContext.getBodyAsString() and parse that string as you wish.

    – taygetos
    Jan 5 at 13:41



















  • This json should actually run into an exception/error. This is just not correct json and it's no wonder that it will cause a parser to fail.

    – maio290
    Jan 3 at 11:22











  • @maio290 okay. that's not really helpful. I'm trying to create a json request with an empty/missing value. So I'm also not surprised that it fails, but I'm looking for another solution, like doing something before parsing.

    – krankit
    Jan 3 at 11:40











  • You cannot use routingContext.getBodyAsJson(); if its not a valid json this will throw an exception. Use routingContext.getBodyAsString() and parse that string as you wish.

    – taygetos
    Jan 5 at 13:41

















This json should actually run into an exception/error. This is just not correct json and it's no wonder that it will cause a parser to fail.

– maio290
Jan 3 at 11:22





This json should actually run into an exception/error. This is just not correct json and it's no wonder that it will cause a parser to fail.

– maio290
Jan 3 at 11:22













@maio290 okay. that's not really helpful. I'm trying to create a json request with an empty/missing value. So I'm also not surprised that it fails, but I'm looking for another solution, like doing something before parsing.

– krankit
Jan 3 at 11:40





@maio290 okay. that's not really helpful. I'm trying to create a json request with an empty/missing value. So I'm also not surprised that it fails, but I'm looking for another solution, like doing something before parsing.

– krankit
Jan 3 at 11:40













You cannot use routingContext.getBodyAsJson(); if its not a valid json this will throw an exception. Use routingContext.getBodyAsString() and parse that string as you wish.

– taygetos
Jan 5 at 13:41





You cannot use routingContext.getBodyAsJson(); if its not a valid json this will throw an exception. Use routingContext.getBodyAsString() and parse that string as you wish.

– taygetos
Jan 5 at 13:41












1 Answer
1






active

oldest

votes


















0














If you really mean that:




ideally, I only want all the int values from the request body




you can simply do the following:



    final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";
final String regularExpression = "([^\d])+";
Pattern pattern = Pattern.compile(regularExpression);
String results = pattern.split(json);
List<Integer> numbers = new ArrayList<>();
for (String result : results) {
try {
numbers.add(Integer.valueOf(result));
} catch (NumberFormatException e) {

}

}
for (int number : numbers) {
System.out.println(number);
}


This would output:



99
2
4
55
0


But this really doesn't give a damn about this being a json. It's just extracting numbers from a string.






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%2f54021174%2fhow-can-i-parse-a-json-object-with-an-empty-value-in-java%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














    If you really mean that:




    ideally, I only want all the int values from the request body




    you can simply do the following:



        final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";
    final String regularExpression = "([^\d])+";
    Pattern pattern = Pattern.compile(regularExpression);
    String results = pattern.split(json);
    List<Integer> numbers = new ArrayList<>();
    for (String result : results) {
    try {
    numbers.add(Integer.valueOf(result));
    } catch (NumberFormatException e) {

    }

    }
    for (int number : numbers) {
    System.out.println(number);
    }


    This would output:



    99
    2
    4
    55
    0


    But this really doesn't give a damn about this being a json. It's just extracting numbers from a string.






    share|improve this answer




























      0














      If you really mean that:




      ideally, I only want all the int values from the request body




      you can simply do the following:



          final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";
      final String regularExpression = "([^\d])+";
      Pattern pattern = Pattern.compile(regularExpression);
      String results = pattern.split(json);
      List<Integer> numbers = new ArrayList<>();
      for (String result : results) {
      try {
      numbers.add(Integer.valueOf(result));
      } catch (NumberFormatException e) {

      }

      }
      for (int number : numbers) {
      System.out.println(number);
      }


      This would output:



      99
      2
      4
      55
      0


      But this really doesn't give a damn about this being a json. It's just extracting numbers from a string.






      share|improve this answer


























        0












        0








        0







        If you really mean that:




        ideally, I only want all the int values from the request body




        you can simply do the following:



            final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";
        final String regularExpression = "([^\d])+";
        Pattern pattern = Pattern.compile(regularExpression);
        String results = pattern.split(json);
        List<Integer> numbers = new ArrayList<>();
        for (String result : results) {
        try {
        numbers.add(Integer.valueOf(result));
        } catch (NumberFormatException e) {

        }

        }
        for (int number : numbers) {
        System.out.println(number);
        }


        This would output:



        99
        2
        4
        55
        0


        But this really doesn't give a damn about this being a json. It's just extracting numbers from a string.






        share|improve this answer













        If you really mean that:




        ideally, I only want all the int values from the request body




        you can simply do the following:



            final String json = "{"arr": [99, [2, 4, ], [[55]], 0]}";
        final String regularExpression = "([^\d])+";
        Pattern pattern = Pattern.compile(regularExpression);
        String results = pattern.split(json);
        List<Integer> numbers = new ArrayList<>();
        for (String result : results) {
        try {
        numbers.add(Integer.valueOf(result));
        } catch (NumberFormatException e) {

        }

        }
        for (int number : numbers) {
        System.out.println(number);
        }


        This would output:



        99
        2
        4
        55
        0


        But this really doesn't give a damn about this being a json. It's just extracting numbers from a string.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 12:10









        maio290maio290

        2,122615




        2,122615
































            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%2f54021174%2fhow-can-i-parse-a-json-object-with-an-empty-value-in-java%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

            MongoDB - Not Authorized To Execute Command

            Npm cannot find a required file even through it is in the searched directory

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith