一、已知數據類型
接收到的數據類型爲Object,如果知道數據的類型可以使用ObjectMapper
進行處理,得到裏面的參數。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
public class Test02 {
public static void main(String[] args) throws IOException {
String str = "{\"one\":\"yes\",\"key\":\"value\"}";
ObjectMapper mapper = new ObjectMapper();
HashMap hashMap = mapper.readValue(str, HashMap.class);
System.out.println(hashMap.toString());
}
}
二、未知數據類型
假如,不清楚數據類型,或者接收到的數據類型有很多種,這樣就需要對接收到的數據,按類型進行分類處理,這就要求對接收到的數據類型進行判斷。
方法一、equals
進行判斷
HashMap<String, String> hashMap = new HashMap<>();
Object object = (Object)hashMap;
if (HashMap.class.equals(object.getClass())){
System.out.println("true");
}
方法二、instanceof
進行判斷
測試一個對象obj是否爲一個類的實例;obj必須爲引用類型,不能是基本類型;obj爲null,則返回false。
HashMap<String, String> hashMap = new HashMap<>();
Object obj = (Object)hashMap;
if (obj instanceof HashMap){
System.out.println("True");
}
方法三、通過class
獲取類型
HashMap<String, String> hashMap = new HashMap<>();
Object object = (Object)hashMap;
String simpleName = object.getClass().getSimpleName();
if ("HashMap".equals(simpleName)){
System.out.println("True");
}