Issue
Let me give some background information:
I have an org.json JSONObject which has all of the values of this JSON object, taken from an API.
"socialMedias" : {
"TWITTER" : "[twitter url]",
"YOUTUBE" : "[youtube url]",
"INSTAGRAM" : "[instagram url]",
"FACEBOOK" : null,
"VIMEO" : "[vimeo url]",
"LINKEDIN" : "[linkedin url]"
}
The thing is, however, that while in one of these calls to the API, there is only one value that is null, but the same value isn't always null, and there can be more than one values that ARE null; Let me illustrate what I mean:
"socialMedias" : {
"TWITTER" : "[twitter url]",
"YOUTUBE" : null,
"INSTAGRAM" : null,
"FACEBOOK" : "[facebook url]",
"VIMEO" : "[vimeo url]",
"LINKEDIN" : "[linkedin url]"
}
That above is something the API could return. Another one:
"socialMedias" : {
"TWITTER" : null,
"YOUTUBE" : null,
"INSTAGRAM" : null,
"FACEBOOK" : null,
"VIMEO" : null,
"LINKEDIN" : null
}
Literally every value in the JSONObject can be null!
Back to the question:
How would I be able to check which values of the JSONObject are null, and only return the ones that are NOT null; So for the very first code block I had, the code would return the TWITTER, YOUTUBE, INSTAGRAM, VIMEO
and LINKEDIN
URLs, and exclude the FACEBOOK
, one because the value of that one is null.
This API returns a JSONObject of the social medias that a user has linked to their account, and puts null if the user hasn't added a value, if it wasn't clear.
I am doing this in Java 17, using the latest version of the org.json
library. Thanks in advance for any help, appreciate it!
Edit: guess i just wasn't using my brain in this post. i realize now that i could just have looped through each value in the socialMedias object and just added all the ones that weren't null into a list... sorry!
Solution
JSONObject socialMedias = new JSONObject(apiResponse).getJSONObject("socialMedias");
JSONArray socialMediaArray = socialMedias.toJSONArray(socialMedias.names());
socialMediaArray.toList().stream().filter(v -> v != null);
Answered By - somayaj
Answer Checked By - Cary Denson (JavaFixing Admin)