我编写这个方法来验证 Json 字符串的类型:
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;
}
所以现在我正在测试这样的方法。
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));
}
它总是返回 false,因为 - if(ex instanceof String[])。 如何检查该数组是否为字符串数组?
最佳答案
基于this java document on arrays我想你可以做这样的事情:
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;}
根据我对 JSONObject 的了解,get 返回与给定键关联的值,因此我对 JSON 的格式做出假设,即“扩展”包含消息的内容。
如果从对象类型到类泛型的转换不能按照我编写的方式进行,我也深表歉意;我根本没有使用 Java 的经验,所以这一切都只是我的猜测。
关于java - 在 Json 字符串中进行类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922811/