0

I want to convert my Blank Json array to the Null Json array.

For ex., My Json array is like "[{}]" and if I got this array then automatically converts to "[]".

My code is like as below :

JsonObject jo = FetchData.getAllItemsAvg(request.getParameter("where"), request.getParameter("lastNum"),request.getParameter("limitAvgNum"));
JsonArray ja = new JsonArray();
ja.add(jo); // Some times ja like "[{}]" .
7
  • 3
    It's not an empty array, it is an array containing a single object with no properties. Commented Apr 12, 2016 at 12:35
  • Okay, Do you know how to convert? Commented Apr 12, 2016 at 12:50
  • Proper answer depends on what is your input (is it string or instance of some kind of JSONArray class) and what JSON library you are using. If it is string then maybe simply replace each {} with empty string. Commented Apr 12, 2016 at 12:58
  • Hi, My code is like : JsonArray ja = new JsonArray(); ja.add(jo); ja.toString().replace("{}", ""); jo = Json Object. I have tried with this but still not working. Thank you. Commented Apr 12, 2016 at 13:02
  • Please add that information to your question. Commented Apr 12, 2016 at 13:06

1 Answer 1

2

Check if the object is empty before adding it to the array. (assuming you're using JsonObject):

JsonObject jo = FetchData.getAllItemsAvg(
                          request.getParameter("where"),
                          request.getParameter("lastNum"),
                          request.getParameter("limitAvgNum"));
JsonArray ja = new JsonArray();
if(!jo.isEmpty()){
    ja.add(jo);
}

For com.google.gson.JsonObject:

JsonObject jo = FetchData.getAllItemsAvg(
                          request.getParameter("where"),
                          request.getParameter("lastNum"),
                          request.getParameter("limitAvgNum"));
JsonArray ja = new JsonArray();
if(!jo.entrySet().isEmpty()){
    ja.add(jo);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you tell me how to check? Because I have tried with following but i'm fail : stackoverflow.com/questions/19170338/… stackoverflow.com/questions/12585492/… And so on..
Yea, i have already tried with this but i'm getting "The method isEmpty() is undefined for the type JsonObject" error.
Which JsonObject are you using (link to API preferred)?
Yea got my answer. Thank you for helping me. I have use "jo.entrySet().size() > 0" instead of "!jo.isEmpty()"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.