1. 程式人生 > >後臺解析前臺傳的JSON陣列

後臺解析前臺傳的JSON陣列

前面講了前臺傳JSON到後臺,只是單獨一個json,這裡說明一下前臺傳JSON陣列到後臺如何接收並轉換

注意,前臺ajax

若為自定義contentType,通過前篇講述的第二種接收方法,獲取jsonStr,之後過程類似。

contentType:"application/x-www-form-urlencoded",//預設值
data : {mydata:jsonArrayFinal},
//data為鍵值對形式

【方法一】

將得到的json陣列字串轉換為 list【使用jackson】:

        String jsonStr = getRequest().getParameter("mydata"
); System.out.println(jsonStr); //json-jackson ObjectMapper objectMapper = new ObjectMapper(); List readValue = null; try { readValue = objectMapper.readValue(jsonStr, List.class); System.out.println("轉換後的list :"+readValue); for
(Object object : readValue) { String objectToJson = objectMapper.writeValueAsString(object); System.out.println("將list[i]轉換為json:"+objectToJson); Person person = objectMapper.readValue(objectToJson, Person.class); System.out.println("每一個list[i]封裝後的model:"
+person); } } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null;

【方法二】

利用JSONArray和JSONObject:
【json - json_lib】

        String jsonStr = getRequest().getParameter("mydata");
        System.out.println(jsonStr);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject(); 
        JSONArray jsonToArray = jsonArray.fromObject(jsonStr);
        ObjectMapper objectMapper = new ObjectMapper();
        for(int i=0;i<jsonToArray.size();i++){

            jsonObject = jsonToArray.getJSONObject(i);
            Person person = (Person) jsonObject.toBean(jsonObject, Person.class);

            System.out.println(person);
        }
        try {
            out(jsonStr);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;