Java:Gson一个java对象转json对象转换的库

A Java serialization/deserialization library to convert Java Objects into JSON and back

文档:

https://github.com/google/gson

https://github.com/google/gson/blob/master/UserGuide.md

解析json为java对象

package com.example.demo;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class GsonDemo {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String json = "{\"name\": \"Tom\", \"age\": 23}";
        Map<String, Object> map = gson.fromJson(json, HashMap.class);
        String name = (String)map.get("name");
        Integer age = ((Double)map.get("age")).intValue();
        System.out.println(name);
        // Tom
        System.out.println(age);
        // 23
    }
}

java转json

package com.example.demojwt;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class GsonDemo {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Tom");
        map.put("age", 23);
        String json = gson.toJson(map);
        System.out.println(json);
        // {"name":"Tom","age":23}
    }
}