zoukankan      html  css  js  c++  java
  • Java——Json字符串与Object互转

        public static void JacksonTest() {//推荐
            //{"MNG001":[{"ID":"1","PWD":"2"}],"MNG002":[{"FaultCode":"1","PWD":"3"}]}
            String json = "{"MNG001":[{"ID":"1","PWD":"2"}],"MNG002":[{"FaultCode":"1","PWD":"3"}]}";
            
            ObjectMapper mapper = new ObjectMapper();
            //把json字符串转为对象
            Object object = null;
            try {
                object = mapper.readValue(json, Object.class);
            } catch (JsonParseException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("JsonToObject-->"+object.toString());
            //把对象转为json字符串
            String objectjson = "";
            try {
                objectjson = mapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            System.out.println("ObjectToJson-->"+objectjson);
        }
        
        public static void GsonTest() {
            //{"MNG001":[{"ID":"1","PWD":"2"}],"MNG002":[{"FaultCode":"1","PWD":"3"}]}
            String json = "{"MNG001":[{"ID":"1","PWD":"2"}],"MNG002":[{"FaultCode":"1","PWD":"3"}]}";
            
            Gson gson = new Gson();
            //把json字符串转对象
            Object object = gson.fromJson(json, Object.class);
            System.out.println("JsonToObject-->"+object.toString());
            //把对象转json字符串
            String objectjson = gson.toJson(object);
            System.out.println("ObjectToJson-->"+objectjson);
        }
  • 相关阅读:
    AQS简介
    原子类案例
    保证线程安全的三个方面
    CAS无锁机制
    乐观锁与悲观锁
    读写锁简介
    重入锁简介
    并发队列Queue
    报错Cannot resolve com.mysq.jdbc.Connection.ping method. Will use 'SELECT 1' instead 问题记录
    Springboot中MyBatis 自动转换 map-underscore-to-camel-case
  • 原文地址:https://www.cnblogs.com/it-mh/p/10729896.html
Copyright © 2011-2022 走看看