String 與 Map 對於 JSON 的互相轉換
在撰寫網頁程式中,前端 HTML 網頁資料,常會把資料組成 JSON 格式再往後端主機傳送,例如:
about_me: {Education: "University", Location: "台灣", Skills: "Springboot, Coding, Javascript, PHP", Notes: "Information Tech"}
後端主機接收時,在 JAVA 的撰寫大部份都會轉成 MAP 方面處理,若要寫入資料庫時,可以使用 ObjectMapper.writeValueAsString(Object value)
,來將 MAP 轉成 JSON 字串。
public ResponseEntity<?> userProfileSave(Locale locale, @RequestBody Map params, HttpServletRequest request, HttpServletResponse response) { responseJson = new HashMap<String,Object>(); responseError = new HashMap<String,Object>(); ObjectMapper oMapper = new ObjectMapper(); Map<String,String> aboutMe = (Map) params.get("aboutMe"); Optional<UserProfile> oUserProfile; try { oUserProfile = userService.getUserProfile(userId, "about_me"); if (oUserProfile.isPresent()) { UserProfile up = oUserProfile.get(); up.setParamValue(oMapper.writeValueAsString(aboutMe)); up.setUpdateDate(sysService.getNowTimestamp()); up.setUpdateUser(userService.getCurrentUser().getId()); userProfileRepo.save(up); } responseJson.put("message", messageSource.getMessage(super.CRUD_SUCCESS, null, locale)); } catch (Exception e) { responseError.put("message", messageSource.getMessage(super.CRUD_FAILURE, null, locale)); logger.debug(e.toString()); } }
若是從資料庫取得這 JSON 字串要轉成 MAP 型態時,則可以使用 ObjectMapper.readValue(String content, Class<T> valueType)
來達成。
public Map<String, String> getUserAboutMe() throws JsonMappingException, JsonProcessingException { Map<String, String> aboutMe = new HashMap<String, String>(); Optional<UserProfile> up = this.getUserProfile("about_me"); if ( up.isPresent()) { // convert JSON string to Map aboutMe = oMapper.readValue(up.get().getParamValue(), Map.class); } return aboutMe; }
- Google 程式庫 也提供 Gson 來將 JSON 字串轉成自定型態
Here is an example of how Gson is used for a simple Class: Gson gson = new Gson(); // Or use new GsonBuilder().create(); MyType target = new MyType(); String json = gson.toJson(target); // serializes target to Json MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
- Gson 將 JSON 字串轉成 MAP 型態範例如下:
/** * JSON 字串轉換成 MAP * @return * @throws JsonProcessingException * @throws JsonMappingException */ private Map<String, String> setParams() throws JsonMappingException, JsonProcessingException { Gson gson = new Gson(); return gson.fromJson(params, new TypeToken<Map<String, String>>() {}.getType()); }
這 Spring Boot 使用 Freemarker 開發 Java Tag 客製標籤 也有實作過。
你必須 登入 才能發表評論。