在java中解析json时,java.util.Vector无法转换为java.util.ArrayList错误

时间:2016-05-04 05:38:26

标签: java json codeigniter codenameone

我想使用arraylist而不是vector,因为ArrayList提供了更好的性能等。但是代码也使用vector。我不明白我什么时候使用json_encode,有时它可以在arraylist中解析,有时也可以在vector中解析。将json解析后的值转换为vector和arraylist有什么不同?是来自模型/控制器(这里使用CI)还是我在java json解析器中做了不同的smth?

codeIgniter控制器:

$data = $this->member->view_members();
header('Content-Type: application/json');
echo json_encode($data);

CI模型:

$queries = $this->db->get('members');
return $queries->result();

JSON:

[{  "id": "1",
    "name": "Magalamind Industries",
    "tableGroup": "Birgunj  rising round table 20",
    "email": "birgunj123@gmail.com",
    "position": "Senior Member",
    "address": "Birgunj",
    "phn": "9876543234",
    "date": "2016-05-03 15:53:51",
    "active": "1"},
 {  "id": "2",
    "name": "Ram kumar Sharma",
    "tableGroup": "Lalitpur round table 5",
    "email": "ram@gmail.com",
    "position": "Recent Member",
    "address": "Patandhoka, lalitpur",
    "phn": "9876567890",
    "date": "2016-05-03 15:53:51",
    "active": "1"}]

带有错误的java json解析msg:java.util.Vector无法强制转换为java.util.ArrayList

ConnectionRequest connectionRequest = new ConnectionRequest() {    
    @Override
    protected void readResponse(InputStream input) throws IOException {
        JSONParser jSONParser = new JSONParser();
        Map<String,Object> parsedData = jSONParser.parse(new InputStreamReader(input));
        response = (ArrayList) parsedData.get("root"); //error msg: java.util.Vector cannot be cast to java.util.ArrayList
    }   
    .........
}

1 个答案:

答案 0 :(得分:2)

jSONParser.parse(new InputStreamReader(input));

是旧的解析方法(注意它在javadocs中已弃用),它使用Hashtables和Vectors。

您需要使用

jSONParser.parseJSON(new InputStreamReader(input));

使用HashMap和ArrayList