从json数组到json对象的转换不正常

Converting from json array to json object not working properly

本文关键字:json 转换 不正常 数组 对象      更新时间:2023-09-26

我创建了一个rest服务,如下所示:

@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);

日志输出如下:日志输出

我正在尝试转换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];