java--09--对象与JSON与Map之间的转换

来源:互联网 发布:linux mv移动多个文件 编辑:程序博客网 时间:2024/05/19 20:18
/**     * 对象转换成JSON数据     * @throws IOException     * @throws SecurityException      * @throws NoSuchFieldException      * @throws IllegalAccessException      * @throws IllegalArgumentException      */    public static void beanCovertJSON() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {        User user = new User();        user.setId(1);        user.setName("dema");        user.setPassword("123");        ObjectMapper objectMapper =new ObjectMapper();        //将对象转换成JSON数据        String JSONUser=objectMapper.writeValueAsString(user);        System.out.println(JSONUser);    }    @SuppressWarnings("deprecation")    public static void beanCovertJSON_02() throws IOException{        JsonGenerator jsonGenerator = null;        ObjectMapper objectMapper = null;        User user = new User();        objectMapper = new ObjectMapper();        //定义输出的位置        jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);        jsonGenerator.writeObject(user);    }    /**     * 对象转成二进制数据     * @throws JsonProcessingException      */    public static void beanConvertByte() throws JsonProcessingException{        User user = new User();        user.setId(1);        user.setName("dema");        user.setPassword("123");        ObjectMapper objectMapper =new ObjectMapper();        byte[] b=objectMapper.writeValueAsBytes(user);    }    /**     * JSON数据转换成Map     * @throws IOException      * @throws JsonMappingException      * @throws JsonParseException      */    public static void JSONConvertMap() throws JsonParseException, JsonMappingException, IOException{        ObjectMapper objectMapper =new ObjectMapper();        String JSONUser="{\"id\":1,\"name\":\"dema\",\"password\":\"123\"}";        Map map=objectMapper.readValue(JSONUser, Map.class);                System.out.println(map.get("id"));      }    /**     * Map转换成JSON     * @throws JsonProcessingException     */    public static void MapConvertJSON() throws JsonProcessingException{        String str=null;        Map map=new HashMap();        map.put("1","a");        map.put("2", "b");        map.put("3", "c");        ObjectMapper objectMapper =new ObjectMapper();        //转换        str=objectMapper.writeValueAsString(map);        System.out.println(str);    }

参考博客:
http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
http://rsy.iteye.com/blog/2303323
未完待续。。。

0 0
原创粉丝点击