Type check in a Json String

1.5k views Asked by At

I wrote this method to verify the types of a Json String:

public static boolean loginMessageCheck(String json){
    boolean ret = false;
    JSONObject o = new JSONObject(json);

    Object ty = o.get("type");
    Object ex = o.get("expansions");
    if(ty instanceof String){
        if(ex instanceof String[]){
            ret = true; 
        }
    }
    return ret; 
}

So now I am testing the method like this.

public static void main(String[] args){
    String[] expansions= {"chat", "test"};
    LoginMessage_Client lm = new LoginMessage_Client("login", expansions);
    Gson gson = new Gson();
    String json = gson.toJson(lm);
    System.out.println(loginMessageCheck(json));
}

It always returns false because of - if(ex instanceof String[]). How can I check if this array is a String array?

2

There are 2 answers

0
aurelius On

because

if(ty instanceof String)

and ty being not a String

0
Brandon Haston On

Based on this java document on arrays I would imagine you could do something such as:

public static boolean loginMessageCheck(String json){
boolean ret = false;
JSONObject o = new JSONObject(json);

Class<?> ex = (o.get("expansions")).getClass();
if(ex.isArray() && (ex.getComponentType() instanceof String)){
    ret = true; 
}
return ret;} 

From what I read about the JSONObject, get returns the value associated with the given key so I'm making assumptions on the format of your JSON being that 'expansions' contains the content of the message.

I also apologize if the conversion from an Object type to a Class generic doesn't work the way I wrote it; I have no experience working in Java at all so it's all just guessing to me.