fasterxml 해석 json 편

39212 단어 자바
1
github demo:https://github.com/FasterXML/jackson-databind
2
maven 의존:
		 <dependency.version.jackson>2.8.8dependency.version.jackson>

        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>${dependency.version.jackson}version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>${dependency.version.jackson}version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>${dependency.version.jackson}version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatypegroupId>
            <artifactId>jackson-datatype-jsr310artifactId>
            <version>${dependency.version.jackson}version>
        dependency>

		
		<dependency>
            <groupId>commons-beanutilsgroupId>
            <artifactId>commons-beanutilsartifactId>
            <version>1.7.0version>
        dependency>
    
JacksonUtil.java
public class JacksonUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JacksonUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        /*
         *   false:        ( :true        json   )
* , Java/C++ ( :/* // )
* : json ( ),
*/
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); /* * false:
, ( , js )
* : json ( ),
*/
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); /* * false:
* , ( : , '\'')
* : , JSON
*/
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); /* * : false_
* , ( :ASCII<32, tab )
* : false( ) , ; true ,
*/
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); /* * , :false, */ objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true); /** * */ objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); /** * null */ objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setLocale(Locale.CHINA); objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false); // locadatetime yyyy-MM-dd HH:mm:ss JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); objectMapper.registerModule(javaTimeModule); } /** * JSON * * @param object * * @return String */ public static String toJSONString(Object object) { String json = ""; if (null == object) { return json; } try { json = objectMapper.writeValueAsString(object); } catch (IOException e) { LOGGER.error("Java JSON !", e); e.printStackTrace(); } return json; } /** * JSON * * @param object * * @param pattern * , "yyyy-MM-dd HH:mm:ss" * @return String */ public static String toJSONString(Object object, String pattern) { String json = ""; if (null == object) { return json; } ObjectMapper mapper = objectMapper; try { DateFormat dateFormat = new SimpleDateFormat(pattern); mapper = mapper.setDateFormat(dateFormat); json = mapper.writeValueAsString(object); } catch (IOException e) { LOGGER.error("Java JSON !", e); e.printStackTrace(); } return json; } /** * json java * * @param json * json * @param typeReference * java * @param * @return */ public static <T> T jsonToBean(String json, TypeReference typeReference) { try { return objectMapper.readValue(json, typeReference); } catch (Exception e) { LOGGER.error("jsonToBeanByTypeReference", e); e.printStackTrace(); } return null; } /** * map JavaBean */ public static <T> T map2bean(Map map, Class<T> clazz) { return objectMapper.convertValue(map, clazz); } }

3 사용
1 매 핑 엔 터 티
jsonToBean:
        List<JsonEntity> jsonEntityList = JacksonUtil.jsonToBean(message, new TypeReference<List<JsonEntity>>(){});
        

메모: enity 는 List 로 정의 하지 마 세 요.
2 직접 읽 기
예시:
    public List<UserEventEntity> parse(String message) throws IOException{
        List<UserEventEntity> list = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(message);
        boolean active = jsonNode.get("Hadoop:service=NameNode,name=FSNamesystem").get("tag.HAState").textValue().equals("active");
        if(active){
            JsonNode innerNode = objectMapper.readTree(jsonNode.get("Hadoop:service=NameNode,name=FSNamesystemState").get("TopUserOpCounts").textValue());
            /**
             * topUserOpCounts   :
             * topUserOpCounts (string) : v (string)   String   v  : ( innerNode)
             *
             *     {
             * 	    "timestamp": "2019-06-25T16:57:11+0800",
             * 	    "windows": [{
             * 		    "windowLenMs": 60000,
             * 		    "ops": [{
             * 			    "opType": "listStatus",
             * 			    "topUsers": [{
             * 					"user": "voyager",
             * 					"count": 82
             *                },
             *                {
             * 					"user": "wave_bi",
             * 					"count": 1
             *                }
             * 			    ],
             * 			    "totalCount": 83
             * 		    }]
             * 	     }]
             *      }
             *
             *       ,  set entity     :
             *     timestamp :    timestamp   xxx
             *     opType    :    opType
             *     opTotalSum:  totalCount    topUsers   ,  user        
             *     userName  :   user
             *     opSum     :   count
             *     windowLenMs:    user 
             *
             *       ,      entity,  user = all ,     opTotalSum
             */
            String timestamp = innerNode.get("timestamp").textValue();
            innerNode.get("windows").forEach(e-> {
                long windowLenMs = e.get("windowLenMs").longValue();
                e.get("ops").forEach(f->{
                    String opType = f.get("opType").textValue();
                    long totalCount = f.get("totalCount").longValue();
                    UserEventEntity a = new UserEventEntity();
                    a.setUserName("all"); //        
                    a.setOpTotalSum(totalCount);
                    a.setOpSum(totalCount);
                    a.setOpType(opType);
                    a.setWindowLenMs(windowLenMs);
                    a.setTimestamp(timestamp);
                    list.add(a);
                    f.get("topUsers").forEach(g->{
                        String user = g.get("user").textValue();
                        long count = g.get("count").longValue();
                        UserEventEntity u = new UserEventEntity();
                        u.setTimestamp(timestamp);
                        u.setWindowLenMs(windowLenMs);
                        u.setOpType(opType);
                        u.setUserName(user);
                        u.setOpSum(count);
                        u.setOpTotalSum(totalCount);
                        list.add(u);
                    });
                });
            });
        }
        return list;
    }

좋은 웹페이지 즐겨찾기