当接收到Gson字符串时,JSON.parse不起作用..."未定义"值

时间:2017-02-15 20:05:10

标签: javascript json ajax gson

Collection lista_interpretes;
lista_interpretes = sistema.buscarInterpretes();
if (!lista_interpretes.isEmpty()) {
  Gson gson = new Gson();
  String test = gson.toJson(lista_interpretes);

  try (PrintWriter out = response.getWriter()) { 
     out.println(test); //USING GSON DOESNT WORKING... [{"cod":"4","name":"Paul"}]
     out.println("{\"cod\":\"4\",\"name\":\"Paul\"}"); /*THIS TEST DOENST USING GSON WORKS. WHATS GOING ON? THE DIFFERENCE IS []*/
  }
}

在Javascript中我使用var X = JSON.parse(req.responseText),但我得到" undefined"来自X.name的值。我试过了

1 个答案:

答案 0 :(得分:0)

您在响应中有多个实体。因为lista_interpretes是Collection。

但是在javascript代码中,您希望获得单个实体。

试试这个:

X = JSON.parse(req.responseText);
X = X[0];
console.log(x.name);