简体   繁体   中英

validate JSON string if the value of parameter is string or an array

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

Had this problem as well and this is how I got around it

In your Data object have

public class Data {
    // This is a generic object whose type is determined when used by GSON
    private Object title;

    // get the type of object and return as string
    public String getTitleObjType() {
            String objType = title.getClass().toString();
        return objType;
    }

    // used if the object is an ArrayList, convert into an ArrayList<Object>
    public ArrayList<String> getTitleArrayList() {
        // Turn the Object into an arraylist
        @SuppressWarnings("unchecked")  // This is to counter the fact that the cast is not type safe
        ArrayList<String> titleArrayList = (ArrayList<String>) title;
        return titleArrayList;
    }

    // used if the object is not an array
    public String getTitleStr() {
            return title.toString();
    }
}

When GSON builds the object it will create and each of these to be either a String or an ArrayList

Then when you want to use the objects, test to see what they are

ArrayList<String> titleValArrayList = new ArrayList<String>();
String titleValStr = "";

if(getTitleObjType.equals("class java.util.ArrayList")) {
         titleValArrayList = getTitleArrayList();
         //do whatever you like
}
else if(getTitleObjType.equals("class java.util.String")) {
         titleValStr = getsTitleStr();
         //do whatever you like
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM