0

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

because

if(ty instanceof String)

and ty being not a String

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.