JSON数组值返回“[{”

时间:2016-09-22 15:00:22

标签: javascript json

我正在编写JSP Web应用程序,并已将Java对象列表转换为JSON数组,并将其设置为属性。现在我正在尝试使用JQuery来解析数组并制作单独的JSON对象,但是我遇到了一个很大的问题,并且无法在网上找到任何其他人处理它的东西。我的servlet创建一个格式正确的JSON数组但是当我像这样访问数组的值时:

orders[0].value;

我的JavaScript控制台只返回“[{”。当我访问对象时

orders[0];

这是一个隐藏数组的隐藏输入,我发现该值如下所示:

value="[{"
                 firstname" : "John", "lastname" :                   "Doe", .....

正如您所看到的,看起来在“[{”之后有一个换行符,它只是将其识别为值。在JavaScript控制台中,Array的其余部分也以不同方式突出显示。

我完全不知道如何解决这个问题。非常感谢任何建议。

这是我的servlet中设置属性的代码:

Object orders = request.getSession().getAttribute("orders");

    String json = new Gson().toJson(orders);
    try {
        ArrayList<String> jsonList = extractObjects(json);
        HttpSession session = request.getSession();
        session.setAttribute("jsonOrders", jsonList);

        //all prints on one line
        System.out.println(jsonList);
    } catch (Exception e) {
        System.out.println("problem parsing JSON");
    }
}

enum ParserState {
    READING_OBJECT, READING_ARRAY
};

//create a JSON array
private ArrayList<String> extractObjects(String array) throws ParseException {
    ParserState state = ParserState.READING_ARRAY;
    StringBuilder currentObject = null;
    ArrayList<String> result = new ArrayList<String>();
    int i = 0;
    int parenthesisBalance = 0;
    for (char c : array.toCharArray()) {
        switch (c) {
        case '{': {
            if (state == ParserState.READING_ARRAY) {
                state = ParserState.READING_OBJECT;
                currentObject = new StringBuilder();
            }
            parenthesisBalance++;
            currentObject.append(c);
            break;
        }
        case '}': {
            if (state == ParserState.READING_ARRAY) {
                throw new ParseException("unexpected '}' ", i);
            } else {
                currentObject.append(c);
                parenthesisBalance--;
                if (parenthesisBalance == 0) {
                    state = ParserState.READING_ARRAY;
                    result.add(currentObject.toString());
                }
            }
            break;
        }
        default: {
            if (state == ParserState.READING_OBJECT) {
                currentObject.append(c);
            }
        }
        }
        i++;
    }
    return result;
}

这是我存储属性的输入:

<input type="hidden" value="${ sessionScope.jsonOrders }" id="orderData" />

使用$('#orderData')使用javascript访问时,我得到了

<input type="hidden" value="[{" 
    firstname":"mike","lastname":"slagle","phonenumber":"17248802249","email":"[pslagle12@gmail.com]","duedate":"2016-11-24","product":"cake","comments":"this="" is="" 11242016="" 11.15","id":16,"price":11.15},="" {"firstname":"mike","lastname":"slagle","phonenumber":"17248802249","email":"[pslagle12@gmail.com]","duedate":"2016-11-24","product":"cake","comments":"this="" 11.15","id":17,"price":11.15},="" {"firstname":"patrick","lastname":"slagle","phonenumber":"7248802249","email":"[pslagle12@gmail.com]","duedate":"2016-11-24","product":"cookies","comments":"this="" cookies="" for="" patrick.","id":18,"price":15.66},="" {"firstname":"betsy","lastname":"horton","phonenumber":"7245443344","email":"[bhorton@hotmail.com]","duedate":"2016-12-17","product":"cupcakes="" ","comments":"this="" cupcakes="" bets.","id":19,"price":65.98},="" {"firstname":"morgan","lastname":"freeman","phonenumber":"864667234","email":"[freeman@hotmail.com]","duedate":"2016-02-15","product":"cake","comments":"this="" a="" cake="" morgan.","id":20,"price":200.75},="" {"firstname":"james","lastname":"boice","phonenumber":"7249983532","email":"[jboice@deadoldguy.net]","duedate":"2016-04-16","product":"cake="" and="" cookies","comments":"this="" an="" 18th="" century="" theologian","id":21,"price":54.95},="" theologian","id":22,"price":54.95}]"="" id="orderData">

我访问返回“[{”:

的值的方式
var orders = $('#orderData')
console.log(orders[0].value);

修改

如果我使用JSP执行此操作:

<c:forEach var="i" items="${ jsonOrders }">
${ i }
</c:forEach>

整个JSON数组的内容都打印在我的页面上,这就是我想要的。看来我正在处理JQuery和JSON数组之间的一些奇怪的相互作用。任何建议将不胜感激。我很难过。从数组中给出一个值的唯一东西是orders [0] .value,它给了我“[{”。

5 个答案:

答案 0 :(得分:0)

订单来自哪里?根据我的观点,我已经看到json值被赋值给变量

json值被赋值为一个字符串,即value="[{...}]",请删除qoutes并像这样分配value=[{....}]

然后访问value[0]["firstname"] or value[0].firstname之类的字段值 您将获得值 John

答案 1 :(得分:0)

var orders = JSON.parse($('#orderData'));
console.log(orders[0].value);

答案 2 :(得分:0)

value="[{"

在那里告诉你value不是JavaScript对象数组,而是String表示。您需要解析String以将其转换为可以查询的实际JavaScript数组。

答案 3 :(得分:0)

如果您不介意导入其他图书馆,可以使用StringEscapeUtils.escapeJson https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html

session.setAttribute("jsonOrders", StringEscapeUtils.escapeJson(jsonList));

然后在javascript中执行此操作:

var orders = JSON.parse($('#orderData').val());

答案 4 :(得分:0)

我选择抛弃这种方法来完全获取我的JSON,而是调用带有get请求的servlet:

$.get('OrdersToJSONServlet', function(responseText) {
    ... 
});

它正在发挥作用。