hi this is more of a java based question but I could use some help here-
i have a stringified (json.stringify) javascript array of strings ["abc","efg","ijk"]
i want to convert it to a json object
JsonObject jsonObject = new Gson().fromJson(arrayOfStrings, JsonObject.class);
com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonArray
i have tried using JsonParser from gson, javax.json.stream but nothing seems to work.
Solved! Go to Solution.
Topics help categorize Community content and increase your ability to discover relevant content.
Views
Replies
Total Likes
If it is only an array of string you want, you can use the below -
List<String> currentGroupIdsList = new ArrayList<String>(Arrays.asList(stringifiedArray.split(",")));
Here stringifiedArray is received from the frontend and converted into simple <List> of strings.
Hope this helps!
Try .fromJson(arrayOfStrings, JsonArray,class) instead of converting it into JsonObject.class
i tried into jsonarray too but that didn't work
Views
Replies
Total Likes
To fix this, you should use the appropriate data structure for deserializing the JSON array. In this case, you should use JsonArray instead of JsonObject since the input is an array of strings.
String arrayOfStrings = "[\"abc\",\"efg\",\"ijk\"]";
// Parse the JSON array into a JsonArray
JsonArray jsonArray = new Gson().fromJson(arrayOfStrings, JsonArray.class);
// Now you can work with the JsonArray as needed
sout(jsonArray); // Output: ["abc","efg","ijk"]
JsonArray object is ready here to access the individual elements within the array if needed
I have tried json array too but that throws an error too.
Views
Replies
Total Likes
Hi @aem_noob ,
I don't know what a full string looks like, but this seems to be JsonArray, try using that class instead.
JsonArray jsonArray = new Gson().toJsonTree(arrayOfStrings).getAsJsonArray();
You could then iterate and read the JsonObject in this array, or form the proper JsonString which would qualify as JsonObject.
Also, check https://www.tutorialspoint.com/how-to-convert-java-array-or-arraylist-to-jsonarray-using-gson-in-jav...
Hope this helps.
Regards,
Nitesh
i tried jsonarray initially but that also threw an exception. the response from front end is a json of array objects which is then filtered to array of strings. the array of strings is not getting cast to jsonarray.
Views
Replies
Total Likes
The array of strings is not getting cast to jsonObject as I have tried it
Views
Replies
Total Likes
If it is only an array of string you want, you can use the below -
List<String> currentGroupIdsList = new ArrayList<String>(Arrays.asList(stringifiedArray.split(",")));
Here stringifiedArray is received from the frontend and converted into simple <List> of strings.
Hope this helps!
this works but isn't it possible to do it via jsonArray or jsonObject?
Views
Replies
Total Likes
Views
Likes
Replies
Views
Likes
Replies
Views
Likes
Replies