简体   繁体   English

使用add属性将JSONObject添加到JSONArray java

[英]Add JSONObject to JSONArray java with add attribute

This is my servlet code. 这是我的servlet代码。 I want add my json object values into a json array.I used add method for that but I'm getting an error. 我想将我的json对象值添加到json数组中,我使用了add方法,但出现错误。 How to add that object to my array? 如何将该对象添加到我的数组? Is there any mistake in my code? 我的代码有什么错误吗?

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
     throws ServletException, IOException {

    try {
        Session ses = HibernateSession.getSession();
        Criteria cr1 = HibernateSession.createCriteria(ses, Product.class);
        cr1.add(Restrictions.eq("Status", "Active"));
        List<Product> plist = cr1.list();

        JSONArray ja1 = new JSONArray();
        for (Product product : plist) {
            JSONObject jo1 = new JSONObject();
            jo1.put("image", product.getProductImages());
            jo1.put("name", product.getName());
            jo1.put("price", product.getPrice());

            ja1.add(jo1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

在此处输入图片说明

尝试使用put()而不是add() ;)

This depends on the libraries which you are using. 这取决于您使用的库。

If you are using org.json.JSONArray then it should be put() but if you are using org.json.simple.JSONArray it's add() . 如果您使用的是org.json.JSONArray ,则应将其put()put()但是如果您使用的是org.json.simple.JSONArray使用add()


I bet you are using org.json.JSONArray . 我敢打赌,您正在使用org.json.JSONArray So try, 所以尝试一下

ja1.put(jo1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM