Java解析Json字符串

Json是一种轻量级的数据交换格式, 其语法格式非常简单

对象:{key : value, key: value...}
数组:[元素1, 元素2 ...]

在平时的开发中,我们都需要使用Json在前后端之间进行数据交换,这里我们主要来看一下Java最方便快捷的解析Json的方式

  1. 谷歌Gson
    将对象转为Json
    String toJson(Object src)

    将json转为对象
    T fromJson(String json, Class classOfT)

    将json转为集合
    T fromJson(String json, Type typeOfT)

    代码示例:

   /**
     * 将对象转换为json
     * @param o
     * @return
     */
    public static String getJsonString(Object o){
        return new Gson().toJson(o);
    }

    /**
     * 将json转为对象
     * @param jsonString
     * @param clazz
     * @return
     */
    public static Object getObjectFromJson(String jsonString, Class clazz){
        return new Gson().fromJson(jsonString, clazz);
    }

    /**
     * 将json转为集合
     * @param jsonString
     * @param type
     * @return
     */
    public static Object getObjectFromJson(String jsonString, Type type){
        return new Gson().fromJson(jsonString, type);
    }

    public static void main(String[] args) {
          // 对象转json
        String objectJson = getJsonString(new Student(18, "jason"));
         //结果:{"age":18,"name":"jason"}
        System.out.println(objectJson);  
      
        // json转对象
          Student student = (Student) getObjectFromJson("{\"age\":18,\"name\":\"jason\"}", Student.class);
          //结果:Student{age=18, name='jason'}
        System.out.println(student);  
      
        // List
          List list = new ArrayList<>();
        list.add(new Student(18, "jason"));
        list.add(new Student(19, "lee"));

          // 集合转json
        String listJson = getJsonString(list);
         //结果:[{"age":18,"name":"jason"},    {"age":19,"name":"lee"}]
        System.out.println(listJson);  
        

          // Json转List
        Type type = new TypeToken>() {
        }.getType();
        ArrayList arrayList = (ArrayList) getObjectFromJson(listJson,           type);
          // 结果:[Student{age=18, name='jason'}, Student{age=19, name='lee'}]
        System.out.println(arrayList.toString());  
          
          // HashMap
          HashMap hashMap = new HashMap<>();
        hashMap.put("name", "jason");
        hashMap.put("age", "18");
      
          // HashMap转json
        String mapJson = getJsonString(hashMap);
        // 结果:{"name":"jason","age":"18"}
        System.out.println(mapJson);

        // json转HashMap
        Type mapType = new TypeToken>() {}.getType();
        HashMap map = (HashMap) getObjectFromJson(mapJson, mapType);
          
        /**
         * 结果
         * key:name, value:jason
         * key:age, value:18
         */
        for (Map.Entry entry : map.entrySet()){
            System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue());
        }
    }
  1. 阿里FastJson
    对象转json
    static String toJSONString(Object object)

    json转对象
    static T parseObject(String text, Class clazz)

    json转List
    static List parseArray(String text, Class clazz)

    json转Map
    static T parseObject(String text, TypeReference type, Feature... features)

    代码示例:

/**
 * 对象转json
 * @param o
 * @return
 */
public static String getJsonString(Object o){
    return JSON.toJSONString(o);
}

/**
 * json转对象
 * @param jsonString
 * @param clazz
 * @return
 */
public static Object getObjectFromJson(String jsonString, Class clazz){
    return JSON.parseObject(jsonString, clazz);
}

/**
 * json转list
 * @param jsonString
 * @param clazz
 * @return
 */
public static Object getArrayFromJson(String jsonString, Class clazz){
    return JSON.parseArray(jsonString, clazz);
}

/**
 * json转map
 * @param jsonString
 * @param typeReference
 * @return
 */
public static Object getMapFromJson(String jsonString, TypeReference typeReference){
    return JSON.parseObject(jsonString, typeReference);
}

public static void main(String[] args) {
        // 对象转json
        String objectJson = getJsonString(new Student(18, "jason"));
        //结果:{"age":18,"name":"jason"}
        System.out.println(objectJson);

        // json转对象
        Student student = (Student) getObjectFromJson(objectJson, Student.class);
        // 结果:Student{age=18, name='jason'}
        System.out.println(student);

        // List
        List list = new ArrayList<>();
        list.add(new Student(18, "jason"));
        list.add(new Student(19, "lee"));

        // List转json
        String listJson = getJsonString(list);
        //结果:[{"age":18,"name":"jason"},{"age":19,"name":"lee"}]
        System.out.println(listJson);

        // json转List
        List students = (List) getArrayFromJson(listJson, Student.class);
        // 结果:[Student{age=18, name='jason'}, Student{age=19, name='lee'}]
        System.out.println(students.toString());
      
        // Map
        HashMap hashMap = new HashMap<>();
        hashMap.put("name", "jason");
        hashMap.put("age", "18");

        // Map转json
        String mapJson = getJsonString(hashMap);
        // 结果:{"name":"jason","age":"18"}
        System.out.println(mapJson);

        // json转HashMap
        TypeReference> typeReference = new TypeReference>() {};
        HashMap map = (HashMap) getMapFromJson(mapJson, typeReference);

        /**
         * 结果
         * key:name, value:jason
         * key:age, value:18
         */
        for (Map.Entry entry : map.entrySet()){
            System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue());
        }
}

你可能感兴趣的:(java,json)