如何在java中访问json的值

时间:2016-08-18 07:17:27

标签: java json

[{
    "year": "2017",
    "org": "1",
    "sub_org": "",
    "sub_org_amt": ""
}, {
    "year": "2017",
    "org": "1",
    "sub_org": "",
    "sub_org_amt": ""
}]

来自我的ajax请求的示例数据:

$.ajax({
    type: 'POST',
    url: 'add.jsp',
    dataType: "json",
    data: {
        action: action,
        tabledata: JSON.stringify(tabledata)
    },
    success: function(data) {


    },
    error: function(data) {
        console.log("error" + data);
    },
    beforeSend: function() {
    },
    complete: function() {
    }
})

如何访问add.jsp中的每个值,以便我可以将它们插入数据库

我试过

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(tabledata);

我有import="net.sf.json.JSONObject",但我在JSONParser

中收到错误

UPDDATE

添加了这一行import ="org.json.simple.parser.JSONParser"

但当我out.println("[" + json.toString() + "]");时,没有显示任何内容

1 个答案:

答案 0 :(得分:0)

我建议使用jackson库来做你想做的事情。

我假设您正在使用servlet处理add.jsp页面,因此在您的servlet中,在包中添加jackson库后添加这些导入

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

然后在doPost方法中添加,从add / jsp转换接收到的json的方法:

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /**
     * Convert json to object
     */
    // 1. get received JSON data from request
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String json = "";
    String line;
    while ((line = br.readLine()) != null) {
        json = json + line;
    }

    #object mapper to map the json to the class
    ObjectMapper objectMapper = new ObjectMapper();

    # object converted by json
    Object object = objectMapper.readValue(json, Object.class);

}