zoukankan      html  css  js  c++  java
  • 如何处理json字符串

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
        private static final ObjectMapper mapper = new ObjectMapper();
        
        static {
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            mapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);
    
            mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
            mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
            mapper.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
        }
        
        public static ObjectMapper getJsonObjectMapper(){
            return mapper;
        }
        
        public static String toJson(Object obj) {
            try {
                return mapper.writeValueAsString(obj);
            } catch (IOException e) {
                logger.error("to json error, ", e);
                return null;
            }
        }
        
        public static <T> T fromJson(String str, Class clazz) {
            try {
                return (T)getJsonObjectMapper().readValue(str, clazz);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    mapper.readTree 可以读取里面的内容

    JsonNode jsonNode = JsonUtil.getObjectMapper().readTree(content);
            JsonNode jsonStatus = jsonNode.get("aa");
            int status = jsonStatus.getIntValue();
    
            JsonNode jsonResults = jsonNode.get("bb");
            Iterator<JsonNode> elements = jsonResults.getElements();
            while (elements.hasNext()) {
                JsonNode json = elements.next();
                JsonNode jsonName = json.get("cc");
                if(jsonName == null || jsonName.isNull()) {
                    continue;
                }
                String jsonNameStr = jsonName.getTextValue();
                if (StringUtils.isBlank(jsonNameStr)) {
                    continue;
                }
               
              
            }
            return false;
  • 相关阅读:
    如何卸载Mysql
    netty4.1.32 pipeline的添加顺序和执行顺序
    protobuf 在win10系统如何编译jar包
    java swing 的各种布局layout
    一些大神的代码功底方面的文章
    图解ByteBuffer
    Eclipse 高亮显示选中的相同变量
    Java synchronized详解(java 线程同步)
    一篇非常全面的 《单例模式》 的讲解的文章
    java中ThreadLocalRandom类和Random类的使用
  • 原文地址:https://www.cnblogs.com/TheQi/p/11392941.html
Copyright © 2011-2022 走看看