자바 에서 자주 사용 되 는 분석 도구 잭 슨 및 fastjson 사용
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2.잭 슨 의 사용실체 클래스 전환 JSON
실체 클래스 를 JSON 형식 데이터 로 변환 하여 전단 으로 되 돌려 줍 니 다.
ObjectMapper obj=new ObjectMapper()를 만 듭 니 다.대상,대상 의 writeValueAsString 방법 은 하나의 실체 클래스(get,set 방법 이 있어 야 함)를 JSON 대상 으로 전환 합 니 다.
package com.lxc.springboot.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // , json, !
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
User user = new User(" ", "888", 20);
ObjectMapper obj = new ObjectMapper();
String jsonObject = obj.writeValueAsString(user);
return jsonObject;
}
// ,
public static class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private String password;
private int age;
public User(String userName, String password, int age) {
this.userName = userName;
this.password = password;
this.age = age;
}
}
}
테스트:집합 전환 JSON
전단 결 과 는 하나의 배열,안 에는 하나의 대상 이다.
package com.lxc.springboot.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
//
List<User> userList = new ArrayList<>();
for(int i = 0; i < 3; i ++) {
userList.add(new User(" "+i, " "+i, 20+i));
}
ObjectMapper obj = new ObjectMapper();
String jsonObject = obj.writeValueAsString(userList);
return jsonObject;
}
// ,
}
테스트:지도 전환 JSON
@RestController
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
// Map
Map<String, Object> map = new HashMap<>();
map.put("name", " ");
map.put("age", 20);
ObjectMapper obj = new ObjectMapper();
String jsonObject = obj.writeValueAsString(map);
return jsonObject;
}
}
전단 결 과 는:대상new Date()변환 JSON
@RestController
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
Date date = new Date();
ObjectMapper obj = new ObjectMapper();
String jsonObject = obj.writeValueAsString(date);
return jsonObject;
}
}
전단 결 과 는 타임 스탬프물론 시간 형식 도 사용자 정의 할 수 있다.
@RestController
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = sdf.format(date); // "2021-06-27 05:19:33"
ObjectMapper obj = new ObjectMapper();
String jsonObject = obj.writeValueAsString(time);
return jsonObject;
}
}
포장 하 다
package com.lxc.springboot.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JavaUtils {
/**
* :
* <dependency>
* <groupId>com.fasterxml.jackson.core</groupId>
* <artifactId>jackson-databind</artifactId>
* <version>2.12.3</version>
* </dependency>
*
* @param object (List)、Map(HashMap)、 (new Date)
* @param format yyyy-MM-dd hh:mm:ss
* @return JSON
*/
public static String getJson(Object object, String format) {
ObjectMapper objectMapper = new ObjectMapper();
//
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//
SimpleDateFormat sdf = new SimpleDateFormat(format);
//
objectMapper.setDateFormat(sdf);
try {
String jsonValue = objectMapper.writeValueAsString(object);
return jsonValue;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static String getJson(Object object) {
return getJson(object, "yyyy-MM-dd hh:mm:ss");
}
}
3.FastJSon 의 사용maven 을 사용 하여 의존 팩 가 져 오기
<!-- aop , JSONObject, fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
상용 방법:(1)JSON.toJSONstring(obejct)-자바 대상 JSON 문자열 변환
(2)JSON.parseObject(string,User.class)-JSON 문자열 을 자바 대상 으로 변환
쓰다
@RestController
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
List<User> userList = new ArrayList<>();
userList.add(new User("1", "1", 20));
String res = JSON.toJSONString(userList);
return res;
}
자바 에서 자주 사용 되 는 분석 도구 잭 슨 및 fastjson 의 사용 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 잭 슨 과 fastjson 의 사용 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.