我在尝试从Web服务中获取数据以JsonArray(com.google.gson.JsonArray)
的形式返回数据时发现了一个问题。在UI
中接收数据时,我会得到undefined
。在java
中,我以下exception
:
Caused by: org.codehaus.jackson.map.JsonMappingException: (was java.lang.IllegalStateException) (through reference chain: com.google.gson.JsonArray["asString"])
我尝试了多种方法,但似乎没有任何作用。请找到我尝试过的代码。
java
@GET
@Path("/fetchData")
@Produces(MediaType.APPLICATION_JSON)
public JsonArray fetchData(@QueryParam("term") String id)
{
List<Object[]> listObj = new ArrayList<Object[]>();
JsonArray jsonArrayObj = new JsonArray();
try
{
listObj = manager.planningData(id.toString());
for (Object[] obj : listObj)
{
JsonObject jsonObj = new JsonObject();
if(obj[0]!=null)
{
jsonObj.addProperty("ID", obj[0].toString());
}
jsonArrayObj.add(jsonObj);
}
}
catch(Exception e)
{
System.out.println(e);
}
return jsonArrayObj;
}
jQuery
$.ajax({
type : 'GET',
url : contextPath+'/rest/fetchDataPlan/fetchData?value='+valueId+'',
dataType:'json',
data : {
term:valueId,
},
success : function(data) {
if (data)
{
console.log("test");
}
else
{
console.log("no work");
}
},
error : function(err) {
console.log("error occurred "+err.message);
}
});
JsonArray
需要在java
中解析为list
,然后返回。然后效果很好。
ArrayList<Object> yourArray = new Gson().fromJson(jsonArrayObj, new TypeToken<List<Object>>(){}.getType());