Issue
this is JSON string 1
{"title":["1","2"], "amount":["1","2"]}
this is JSON string 2
{"title":"", "amount":""}
string 1 is created when I enter values in form and string 2 is created when I dont, I want to know if the string is in format 1 that is title is an array ["1", "2"] or format 2 that is title is just a string "" on the server side in a servlet, before I parse it. is there any way of doing so?
this is my previous question, How do I parse this JSON string using GSON in servlet
which is solved but as you can see there i have class Data which has instance variables of type ArrayList, so when I parse it with this line
Data data = gson.fromJson(param, Data.class);
it throws exception
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 24
because as I have declared ArrayList, it expects array only in json to parse it without any exceptions....but when I dont enter values in my form it doesnt create json string as
{"title":[], "amount":[]}
rather it creates like this
{"title":'', "amount":''}
which has string as value, which causes parsing to throw exception
Solution
Check Google GSON it allows you to parse JSON server side.
It goes something like this:
String jsonString = request.getParameter("jsonParemeter");
Gson gson = new Gson();
Map fromJsonMap = gson.fromJson(jsonString, HashMap.class);
Object object = fromJsonMap.get("title");
if (object instanceof Collection) {
// then is it's your array
}
else {
// it's not
}
If, for example, I run the following example code:
String json1 = "{\"title\":[\"1\",\"2\"], \"amount\":[\"1\",\"2\"]}";
String json2 = "{\"title\":\"\", \"amount\":\"\"}";
Gson gson = new Gson();
HashMap map = gson.fromJson(json1, HashMap.class);
HashMap map2 = gson.fromJson(json2, HashMap.class);
System.out.println(map);
System.out.println(map2);
System.out.println(map.get("amount").getClass());
System.out.println(map2.get("amount").getClass());
I get as output:
{amount=[1, 2], title=[1, 2]}
{amount=, title=}
class java.util.ArrayList
class java.lang.String
If I understood you correctly I think it suits you 100%
UPDATE
Since you are trying to deserialize your JSON string directly to a Data object, if you want to keep doing that direct deserialization you have to use a custom deserialization mechanism
Answered By - pabrantes