자바 에서 자주 사용 되 는 분석 도구 잭 슨 및 fastjson 사용

8203 단어 Javajacksonfastjson
1.maven 설치 jackson 의존

<!-- 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 의 사용 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기