我创建了这样的休息服务:
@GET
@Path("/getsummary")
@Produces("application/json")
public Response summary()
{
VoltDAOImpl voltDao = new VoltDAOImpl();
Map<String ,List<HashMap<String,String>>> returnList= voltDao.getOrderDetails("PEAKM" , "Hydra" ,
"" , voltDao.client,"notional" ,1000);
List<HashMap<String,String>> totalSlpSummaryList = returnList.get("total_slp_summary");
List<HashMap<String,String>> totalSlpSummaryBySideList = returnList.get("total_slp_summary_by_side");
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json1 = null;
String json2 = null;
String json3 = null;
try {
json1 = ow.writeValueAsString(totalSlpSummaryList);
json2 = ow.writeValueAsString(totalSlpSummaryBySideList);
json3="["+json1+","+json2+"]";
//json3 = json1 + "\n" + json2;
System.out.println(json1);
System.out.println(json2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.status(200).entity(json3).build();
}
然后,我在像这样的JavaScript中使用它:
var rootURL = "http://localhost:8181/RestServiceProject/rest/WebService/getsummary";
function findBySummary() {
console.log("inside loading grid");
var returnval1;
$.ajax({
type: 'GET',
url: rootURL,
dataType: "json",
async: false,
success: function(json3){
returnval1 = json3;
console.log(returnval1);
}
});
return returnval1;
}
console.log(returnval1);
返回以下结果:
returnval1
稍后我打电话给
findBySummary();
并执行以下操作: var json3 = findBySummary();
var json4 = json3[0];
console.log("json4");
console.log(json4);
var json_temp = JSON.stringify(json4);
console.log("json_temp")
console.log(json_temp);
var json_temp1 = json_temp[0];
console.log("json temp1");
console.log(json_temp1);
以下是此的日志输出:
log output
我正在尝试转换json_temp,即:
[{"total_exec_qty":"286595","total_notional":"21820771.72","total_wt_arr_last_slp":"2.4364","total_num_ords":"1630","total_wt_ivwap_slp":"6.0969","total_wt_arr_slp":"1.7889","total_ord_qty":"576991"}]
到这个(json_temp1):
{"total_exec_qty":"286595","total_notional":"21820771.72","total_wt_arr_last_slp":"2.4364","total_num_ords":"1630","total_wt_ivwap_slp":"6.0969","total_wt_arr_slp":"1.7889","total_ord_qty":"576991"}
但是为什么我只为json_temp1得到
[
? 最佳答案
请注意,JSON.stringify(json4)
返回一个字符串。
因此,代码json_temp[0]
将返回此字符串中的第一个元素。
您想要的是:var json_temp1 = json4[0];
并不是:var json_temp1 = json_temp[0];
以下代码不符合您的需要:
var json_temp = JSON.stringify(json4);
console.log("json_temp")
console.log(json_temp);
var json_temp1 = json_temp[0];