Javabean轉json字符串

用maven開發web時我都用的maven提供的依賴,本地的jar一直導不進去,然後我隨便找了個Google的json的jar包,裏面的方法少的可憐

pom中寫入依賴

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

現在我有的是JavaBean的數組,我需要轉成json字符串數組

先說一個JavaBean對象轉成一個json字符串

JSONObject.toJSONString(Map map)方法參數是一個map集合,返回一個json字符串{}

如果是JavaBean數組

提供了一個方法JSONArray.toJSONString(List list)方法參數是一個列表,返回json字符串[{},{}],這個list只需要是Map類型的就行

<%
SelectInfo selectInfo = new SelectInfo();
TotalInfo[] totalInfos = selectInfo.selectTotalInfo();
List<Map> list = new ArrayList<>();
for(TotalInfo totalInfo : totalInfos){
    Map map = new HashMap();
    map.put("specialty",totalInfo.getSpecialty());
    map.put("grade",totalInfo.getGrade());
    map.put("studentNo",totalInfo.getStudentNo());
    map.put("studentName",totalInfo.getStudentName());
    map.put("studentSex",totalInfo.getStudentSex());
    map.put("subjectName",totalInfo.getSubjectName());
    map.put("studentScore",totalInfo.getStudentScore());
    list.add(map);
    //String strJson = JSONObject.toJSONString(map);
    //out.write(strJson);
}
String jsonString = JSONArray.toJSONString(list);
out.write(jsonString);
%>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章