Spring json和 Map, List等bean的转换

102 篇文章 2 订阅
21 篇文章 0 订阅

Spring  json和 Map, List等bean的转换,代码如下:


1: 将map集合转换成json字符串和将json字符串转换成map

1. [代码][Java]代码 

Map<String,Object> map = newHashMap<String,Object>();
map.put("method","json");
map.put("param",null);
map.put("time","2015-01-23 10:54:55");
ObjectMapper mapper = newObjectMapper();
mapper.writeValueAsString(map);

 

2. [代码][Java]代码    

 
publicstaticvoidreadJson2Map(String json) {
        ObjectMapper objectMapper = newObjectMapper();
        try{
 
            //将json字符串转成map结合解析出来,并打印(这里以解析成map为例)
            Map<String, Map<String, Object>> maps = objectMapper.readValue(
                    json, Map.class);
            System.out.println(maps.size());
            Set<String> key = maps.keySet();
            Iterator<String> iter = key.iterator();
            while(iter.hasNext()) {
                String field = iter.next();
                System.out.println(field + ":"+ maps.get(field));
            }
        }catch(JsonParseException e) {
            e.printStackTrace();
        }catch(JsonMappingException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
readJson2Map(json);

 

public class Jackson {  
    /* 
     * 
     * Class Descripton goes here. 
     * 
     * @class Jackson 
     * @version  1.0 
     */  
    public  static JsonGenerator jsonGenerator = null;  
    private static ObjectMapper mapper = new ObjectMapper();  
    public static void main(String[] args) {  
        Student student = new Student();  
        student.setIsstudent(true);  
        student.setUid(1000);  
        student.setUname("xiao liao");  
        student.setUpwd("123");  
        student.setNumber(12);  
          
        Map<String, Student> stuMap = new HashMap<String, Student>();  
        stuMap.put("1", student);  
        stuMap.put("2", student);  
          
        List<Object> stuList = new ArrayList<Object>();  
        List<Student> stuList1 = new ArrayList<Student>();  
        stuList1.add(student);  
        student=  new  Student();  
        student.setIsstudent(false);  
        student.setUid(200);  
        student.setUname("xiao mi");  
        stuList1.add(student);  
          
        stuList.add(student);  
        stuList.add("xiao xin");  
        stuList.add("xiao er");  
        stuList.add(stuMap);  
          
        //readJson2List();  
        try {  
            //readJson2Array();  
            //writeArray2Json(array);  
            //writeJson2List();  
            //writeEntity2Json(student);  
            writeJson2Entity();  
            //writeMap2Json(stuMap);  
            //writeList2Json(stuList1);  
              
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
     /** 
      *  
      * <code>writeEntity2Json</code> 
      * @description: TODO(实体类转换成json)  
      * @param object 
      * @throws IOException 
      */  
     public static void writeEntity2Json(Object object) throws IOException {  
           mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object );  
           mapper.writeValue( System.out,object );  
           
     }  
     /** 
      *  
      * <code>writeArray2Json</code> 
      * @description: TODO(数组转换成json数组)  
      * @param object 
      * @throws IOException 
      */  
     public static void writeArray2Json(Object object) throws IOException {  
           
         // writeValue具有和writeObject相同的功能  
         mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object );  
         mapper.writeValue(System.out,object );  
           
     }  
     /** 
      *  
      * <code>writeMap2Json</code> 
      * @description: TODO(map对象转换成json对象)  
      * @param object 
      * @throws IOException 
      */  
     public static void writeMap2Json(Object object) throws IOException {  
           
         System.out.println("使用ObjectMapper-----------");  
         // writeValue具有和writeObject相同的功能  
         System.out.println("==>"+mapper.writeValueAsString(object));  
         mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object );  
         mapper.writeValue( System.out , object );  
     }  
     /** 
      *  
      * <code>writeList2Json</code> 
      * @description: TODO(list转换成json)  
      * @param object 
      * @throws IOException   
      */  
     public static void writeList2Json(Object object) throws IOException {  
         System.out.println("==>"+mapper.writeValueAsString(object));  
         mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object );  
         mapper.writeValue( System.out , object );  
     }  
     /** 
      *  
      * <code>writeJson2Entity</code> 
      * @description: TODO(json转换成实体)  
      * @throws IOException 
      */  
     public static void writeJson2Entity() throws IOException {  
         System.out.println("json串转换成entity-------------");  
//       File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");  
//       FileInputStream inputStream = new FileInputStream(file);  
//       Student student = mapper.readValue(inputStream,Student.class);  
//       System.out.println(student.toString());  
         //漂亮输出  
         //mapper.defaultPrettyPrintingWriter().writeValueAsString(value);  
      
         String json = "{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true}";  
         Student student1 = mapper.readValue(json,Student.class);  
         System.out.println("json2:"+student1.toString());  
     }  
     /** 
      *  
      * <code>writeJson2List</code> 
      * @description: TODO(json专程list对象)   
      */  
     public static void writeJson2List() throws IOException {  
         System.out.println("json串转换成entity-------------");  
         File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");  
         FileInputStream inputStream = new FileInputStream(file);  
         Student student = mapper.readValue(inputStream,Student.class);  
         System.out.println(student.toString());  
           
         String json = "[{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true},{\"uid\":200,\"uname\":\"xiao mi\",\"upwd\":null,\"number\":0.0,\"isstudent\":false}]";  
         List<LinkedHashMap<String, Object>> s= mapper.readValue(json,List.class);  
         for (int i = 0; i < s.size(); i++) {  
             LinkedHashMap<String, Object> link = s.get(i);  
             Set<String>  key = link.keySet();  
             for (Iterator iterator = key.iterator(); iterator.hasNext();) {  
                String string = (String) iterator.next();  
                System.out.println(string+"==>"+link.get(string));  
                  
            }  
             System.out.println("json:"+i+""+s.get(i).toString());  
              
        }  
     }  
     /** 
       * JSON转换为List对象 
       */  
      public static void readJson2List() {  
       String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"  
         + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";  
       try {  
        List<LinkedHashMap<String, Object>> list = mapper.readValue(  
          json, List.class);  
        System.out.println(list.size());  
        for (int i = 0; i < list.size(); i++) {  
         Map<String, Object> map = list.get(i);  
         Set<String> set = map.keySet();  
         for (Iterator<String> it = set.iterator(); it.hasNext();) {  
          String key = it.next();  
          System.out.println(key + ":" + map.get(key));  
         }  
        }  
       } catch (JsonParseException e) {  
        e.printStackTrace();  
       } catch (JsonMappingException e) {  
        e.printStackTrace();  
       } catch (IOException e) {  
        e.printStackTrace();  
       }  
      }  
      /** 
       * JSON转换为List对象 
       */  
      public static void readJson2Array() {  
          String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"  
              + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";  
          try {  
              Student[] students = mapper.readValue(json, Student[].class);  
              for (Student student : students) {  
                System.out.println(">"+student.toString());  
            }  
          } catch (JsonParseException e) {  
              e.printStackTrace();  
          } catch (JsonMappingException e) {  
              e.printStackTrace();  
          } catch (IOException e) {  
              e.printStackTrace();  
          }  
      }  
  
}  


上面的代码则是演示数组,list等对象如何转换为json的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中,将POJO对象转换Map对象可以使用Java的反射方法和Jackson库来实现。首先,我们需要使用Java的反射方法`getDeclaredFields()`来获取POJO对象中的字段列表,包括私有字段。然后,我们可以使用Jackson库的ObjectMapper类将POJO对象转换为字符串,并根据定义的格式将其转换Map对象。在这个过程中,ObjectMapper会读取POJO对象中的@JsonFormat注解,根据定义的格式进行转换。以下是具体的实现代码: ```java private Map<String, Object> toMap(Object obj) { Map<String, Object> result = new HashMap<>(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String key = field.getName(); Object value; try { value = field.get(obj); } catch (Exception e) { log.warn("取不到对象中名为 " + field.getName() + " 的值,将其置为空。", e); continue; } result.put(key, value); } return result; } ``` 这段代码中,我们首先使用`getDeclaredFields()`方法获取POJO对象中的所有字段。然后,我们通过循环遍历每个字段,将其名称作为Map中的键,并通过`field.get(obj)`方法获取该字段的值。最后,将键值对添加到结果Map中并返回。 请注意,上述代码中的日志记录是可选的,可以根据需要进行调整。同样地,这个方法也可以根据具体的需求进行调整和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [说说如何把一个POJO形式的Bean对象转换Map形式](https://blog.csdn.net/deniro_li/article/details/117394290)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值