paulwong

JSON转JAVA BEAN


import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ColumnControllerTest {
    
    private Logger logger = LoggerFactory.getLogger(ColumnControllerTest.class);
    
    
    @Test
    public void testTest()
    {
        ObjectMapper mapper = new ObjectMapper();
        /*AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
        // make deserializer use JAXB annotations (only)
        mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
        // make serializer use JAXB annotations (only)
        mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
*/
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
        String userStr = "{\"username\":\"paul\",\"email\":\"paul@paul.com\"}";
        try {
            TypeReference<TestUser> temp = new TypeReference<TestUser>(){};
            TestUser testUser = mapper.readValue(userStr, temp);
            System.out.println(testUser.toString());
            
            String result = mapper.writeValueAsString(testUser);
            System.out.println(result);
            
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

posted on 2015-11-18 13:30 paulwong 阅读(453) 评论(0)  编辑  收藏 所属分类: J2SE


只有注册用户登录后才能发表评论。


网站导航: