Java中关于JSON对象类型和字符串类型之间互相转化(2)


 /**
  * 将MAP转为Json Map参数
  *
  * @param map
  * @return
  * @throws IOException
  */
 public static String toJson(Map<String, Object> map) {
  String json = "[]";
  ObjectMapper mapper = new ObjectMapper();
  StringWriter sw = new StringWriter();
  try {
   JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
   mapper.writeValue(gen, map);
   gen.close();
   
   json = sw.toString();
  } catch (JsonGenerationException e) {
   json = "[]";
   logger.error("----1------toJson JsonGenerationException:\n" + e);
  } catch (JsonMappingException e) {
   json = "[]";
   logger.error("----2------toJson JsonMappingException:\n" + e);
  } catch (IOException e) {
   json = "[]";
   logger.error("----3------toJson IOException:\n" + e);
  }

return json;
 }

/**
  * 将JSON字符串 转换为对象
  *
  * @author weiyuanhua
  * @date 2010-11-18 下午02:52:13
  * @param jsonStr
  *            JSON字符串
  * @param beanClass
  *            泛型对象
  * @param field
  *            对象中需要忽略的属性
  * @return
  */
 public static Object jsonToObject(String jsonStr, Class<?> beanClass)
   throws JsonParseException, JsonMappingException, IOException {
  ObjectMapper objectMapper = new ObjectMapper();
  return objectMapper.readValue(jsonStr.getBytes(), beanClass);
 }

public static Object jsonToObject(String jsonStr, String encoding,
   Class<?> beanClass) throws JsonParseException,
   JsonMappingException, IOException {
  ObjectMapper objectMapper = new ObjectMapper();
  return objectMapper.readValue(jsonStr.getBytes(encoding), beanClass);
 }

public static Map<String, Object> parseJSON2Map(String jsonStr)
   throws JsonParseException, JsonMappingException, IOException {
  ObjectMapper objectMapper = new ObjectMapper();
  return objectMapper.readValue(jsonStr, Map.class);
 }
 
 //不需要记性属性的忽略 
    public static String toJson(Object object,String filterName) {
     ObjectMapper mapper = new ObjectMapper();
        String  json = "[]"; 
        try { 
            FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName, SimpleBeanPropertyFilter.serializeAllExcept()); 
            json = mapper.writer(filterProvider).writeValueAsString(object); 
        } catch (Exception e) { 
            json = "[]"; 
            logger.error("----1------toJson Exception:\n" + e);
        }
       
        return json;
    }
   
    /*
    *
    * @param object 需要进行json序列化的类  可以是任何复杂的类
    * @param args 需要进行过滤的属性名称 类对象名称或者一些属性名称都可以进行过滤
    * */ 
 public static String toJson(Object object, String[] args, String filterName) {
  String json = "[]";
  ObjectMapper mapper = new ObjectMapper();
  try {
   FilterProvider filterProvider = new SimpleFilterProvider()
     .addFilter(filterName,
       SimpleBeanPropertyFilter.serializeAllExcept(args));
   json = mapper.writer(filterProvider).writeValueAsString(object);
  } catch (Exception e) {
   json = "[]";
   logger.error("----1------toJson Exception:\n" + e);
  }

return json;
 }
 
 public static void main(String[] args) {
  User user = new User(12, "aaa", "123456", new Date());
//  String result = toJson(user, "id");
  String result = toJson(user);
  System.out.println(result);
  List list = new ArrayList();
  list.add(0,"name");
  list.add(1,"favorite");
  String li = toJson(list);
  System.out.println(li);
 
  Map<String,String> map = new HashMap<String,String>();
  map.put("password", "123");
  map.put("name", "clark");
  map.put("call", "wowo");
  String mr = toJson(map);
  System.out.println(mr);
 
  Date d = new Date();
  String jsonStr = "{\"id\":23,\"name\":\"44444\"}";
  try {
   User u = (User)jsonToObject(jsonStr, User.class);
   System.out.println(u.getName());
   
   
   Map<String, Object> mapResult = parseJSON2Map(jsonStr);
   Set<String> key = mapResult.keySet();
   Iterator iter = key.iterator();
   while(iter.hasNext()){
    String k = (String) iter.next();
    System.out.println(mapResult.get(k));
   }
   
  } catch (JsonParseException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

在应用测试中的Model类---User.java类如下:

package com.clark.model;

import java.util.Date;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/38a0381c0009d4af6316784467caedd5.html