zoukankan      html  css  js  c++  java
  • Java中让fastJson识别Colloction和Map中的泛型类

    由于fastJson的高效性,最近采用fastJson来做序列化并存储数据,但出现了一个麻烦的问题,如果将Map<K,V>这样的类型序列化,反序列化就会不尽人意,有以下尝试:

    • 使用JSON.parseObject(json):得到的结果是无类型Map,其value为JSONObject。
    • 使用JSON.parseObject(json, Map.class):结果同上。

    虽然说使用JSONObject.toJavaObject(V.class)也能够完成所求,但是这样的方法还是略麻烦,而且如果对key也要利用,那就要对key和value都来一下。在查阅资料后终于找到了正确的方案:TypeReference类。

    简单介绍下,TypeReference类是Java给出的用于明确指定反序列化类型的类,其<>中放入一个复合类型,其参数为复合类型的Class对象,使用示例(我对该方法针对Map做的一个封装)如下:

        public static <K, V> Map<K, V> json2Map(String path, Class<K> k, Class<V> v) throws Exception {
            return JSON.parseObject(path, new TypeReference<Map<K, V>>(k, v) {
            });
        }
    

    测试如下:

    public class TypeReferenceTest {
        public static <K, V> Map<K, V> json2Map(String path, Class<K> k, Class<V> v) throws Exception {
            return JSON.parseObject(path, new TypeReference<Map<K, V>>(k, v) {
            });
        }
    
        public static class Person {
            private String name;
            private String age;
    
            public Person(String name, String age) {
                this.name = name;
                this.age = age;
            }
    
            public void introduce() {
                System.out.println("My name is " + name + " and I am " + age + ".");
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getAge() {
                return age;
            }
    
            public void setAge(String age) {
                this.age = age;
            }
        }
    
        public static void main(String[] args) throws Exception {
            Map input = new HashMap();
            input.put(0L, new Person("Cielo", "3"));
            input.put(1L, new Person("Vicky", "1"));
            String str = JSON.toJSONString(input);
            Map<Long, Person> map = json2Map(str, Long.class, Person.class);
            map.forEach((key, value) -> {
                System.out.println(key);
                value.introduce();
            });
        }
    }
    

    测试结果如下:

    0
    My name is Cielo and I am 3.
    1
    My name is Vicky and I am 1.
    

    可见,能够成功实现多层序列化。

  • 相关阅读:
    Kibana: missing authentication credentials for REST request
    MySQL命令速记
    VIM常用命令简记
    Linux常用命令简记
    袁永福的C#编程书籍,电子工业出版社出版。
    发布DCWriter电子病历文本编辑器
    袁永福的博客系列文章链接集合
    ssh隧道 的命令行和 sshd 服务的配置(gatePort)
    PureMVC(AS3)剖析:设计模式(二)
    Python应用与实践
  • 原文地址:https://www.cnblogs.com/cielosun/p/10863687.html
Copyright © 2011-2022 走看看