java--09--대상과 JSON과 맵 사이의 전환

5022 단어 jsonmap
/** *      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미완성 미속...

좋은 웹페이지 즐겨찾기