使用FastJson将List集合put到JSONObject,通过JSONObject对象obj获取getJSONObject(key)获取集合List出错,类型转换异常JSONArray不能够转换成JSONObject。
ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject] with root cause
java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject
看看put源码
复制收展Javapublic Object put(String key, Object value) {
return this.map.put(key, value);
}
- 1
- 2
- 3
调用的是com.alibaba.fastjson.util.AntiCollisionHashMap中的方法。
复制收展Javatransient AntiCollisionHashMap.Entry<K, V>[] table;
public V put(K key, V value) {
if (key == null) {
return this.putForNullKey(value);
} else {
int hash = false;
int hash;
if (key instanceof String) {
hash = hash(this.hashString((String)key));
} else {
hash = hash(key.hashCode());
}
int i = indexFor(hash, this.table.length);
for(AntiCollisionHashMap.Entry e = this.table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
return oldValue;
}
}
++this.modCount;
this.addEntry(hash, key, value, i);
return null;
}
}
void addEntry(int hash, K key, V value, int bucketIndex) {
AntiCollisionHashMap.Entry<K, V> e = this.table[bucketIndex];
this.table[bucketIndex] = new AntiCollisionHashMap.Entry(hash, key, value, e);
if (this.size++ >= this.threshold) {
this.resize(2 * this.table.length);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
我们发现使用JSONObject使用一个数组来维护的。
transient AntiCollisionHashMap.Entry<K, V>[] table;
并且集合等类型没有转换类型,直接存进去。那说明获取的时候转换了。
获取方法的源码
发现getJSONObject能处理三种类型。JSONObject类型、Map类型以及String都会转换成JSONObject,所以没有List不能够获取List类型的value.
看看getJSONArray是可以获取List类型的,
如果必须要获取可以先用getJSONArray获取数据,然后再转换成List
复制收展JavaJSONArray articles = obj.getJSONArray("articles");
List<Article> list = JSONObject.parseArray(articles.toJSONString(), Article.class);
- 1
- 2
获取方法的源码
复制收展Javapublic JSONObject getJSONObject(String key) {
Object value = this.map.get(key);
if (value instanceof JSONObject) {
return (JSONObject)value;
} else if (value instanceof Map) {
return new JSONObject((Map)value);
} else {
return value instanceof String ? JSON.parseObject((String)value) : (JSONObject)toJSON(value);
}
}
public JSONArray getJSONArray(String key) {
Object value = this.map.get(key);
if (value instanceof JSONArray) {
return (JSONArray)value;
} else if (value instanceof List) {
return new JSONArray((List)value);
} else {
return value instanceof String ? (JSONArray)JSON.parse((String)value) : (JSONArray)toJSON(value);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21