An overview of the

As an object-oriented developer, you encounter a lot of Json processing in your daily business code. This article is based on the most common libraries, gson, Fastjson, Jackson, for the record only.

Basis of preparation

Start by creating a Java object for testing

role

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-10 * /
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {

    private String roleName;

}
Copy the code

Here we create a composite nested object user

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-10 * /
@Data
public class User {

    private String userName;
    private List<Role> roles;
}
Copy the code

User groups

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-11 * /
@Data
public class UserGroup implements Serializable {

    private String groupName;
    private Map<String, User> idNumber;

}
Copy the code

The menu

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-10 * /
@Data
@AllArgsConstructor
public class Menu {

    @SerializedName("menu_name")
    private String menuName;

}
Copy the code

department

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-11 * /
@Data
@AllArgsConstructor
public class Dept {
    private String deptName;
}
Copy the code

Type adapter

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-11 * /
public class DeptAdapter implements JsonSerializer<Dept> {

    @Override
    public JsonElement serialize(Dept dept, Type type, JsonSerializationContext jsonSerializationContext) {

        JsonObject deptObject = new JsonObject();
        deptObject.addProperty("dept_name", dept.getDeptName());

        returndeptObject; }}Copy the code

Gson

Maven rely on

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
Copy the code

Unit testing

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-10 * /
class GsonTest {

    / * * * {" userName ":" admin ", "roles" : [{" roleName ":" system administrator "}, {" roleName ", "general manager"}]} * /
    @Test
    void toJson(a) {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");
        User user = new User();
        user.setUserName("admin");
        user.setRoles(Arrays.asList(role1, role2));

        // Object to json
        String json = new Gson().toJson(user);
        System.out.println(json);
    }

    / * * * {" userName ":" admin ", "roles" : [{" roleName ":" system administrator "}, {" roleName ", "general manager"}]} * /
    @Test
    void toJson2(a) {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");
        User user = new User();
        user.setUserName("admin");
        user.setRoles(Arrays.asList(role1, role2));

        String json = new GsonBuilder().create().toJson(user);
        System.out.println(json);
    }

    /** * User(userName=admin, roles=[Role(roleName= administrator), Role(roleName= administrator)]) */
    @Test
    void fromJson(a) {
        String json = "{\ userName \" : \ "admin \", \ "roles \" : [{\ "roleName \" : \ \ "system administrator"}, {\ "roleName \" : \ "general manager \}]}";
        User user = new Gson().fromJson(json, User.class);
        System.out.println(user);
    }

    The admin / * * * * {" userName ":" admin ", "roles" : {" roleName ":" super administrator "}} * /
    @Test
    void createJsonObject(a) {

        JsonObject role = new JsonObject();
        role.addProperty("roleName"."Super Administrator");

        JsonObject user = new JsonObject();
        user.addProperty("userName"."admin");
        user.add("roles", role);

        String username = user.get("userName").getAsString();
        System.out.println(username);
        System.out.println(user);
    }

    /** * admin */
    @Test
    void json2Object(a) {

        String json = "{\ userName \" : \ "admin \", \ "roles \" : [{\ "roleName \" : \ \ "system administrator"}, {\ "roleName \" : \ "general manager \}]}";

        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
        String userName = jsonObject.get("userName").getAsString();
        System.out.println(userName);
    }


    / * * * [{" roleName ":" system administrator "}, {" roleName ", "general manager"}] * /
    @Test
    void list2Json(a) {

        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");
        String json = new Gson().toJson(Arrays.asList(role1, role2));

        System.out.println(json);
    }

    /** * [Role(roleName= administrator), Role(roleName= administrator)] */
    @Test
    void json2List(a) {
        String json = "[{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}"]";
        List<Role> roles = new Gson().fromJson(json, new TypeToken<List<Role>>() {}.getType());

        System.out.println(roles);
    }

    / * * * [{" roleName ":" system administrator "}, {" roleName ", "general manager"}] * /
    @Test
    void json2Array(a) {
        String json = "[{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}"]";
        JsonArray jsonArray = JsonParser.parseString(json).getAsJsonArray();

        System.out.println(jsonArray);
    }

    /** * {"userName":"admin"} */
    @Test
    void map2Json(a) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userName"."admin");

        String json = new Gson().toJson(hashMap);
        System.out.println(json);
    }

    /** * admin */
    @Test
    void json2Map(a) {
        String json = "{\"userName\":\"admin\"}";
        HashMap hashMap = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {}.getType());

        System.out.println(hashMap.get("userName"));
    }


    /** * Default field conversion rule, the same field name * {"roleName":" super administrator "} */
    @Test
    void setFieldNamingPolicy1(a) {

        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .create();

        Role role = new Role("Super Administrator");
        String json = gson.toJson(role);
        System.out.println(json);
    }

    /** * Convert json field names to uppercase format * {"RoleName":" super administrator "} */
    @Test
    void setFieldNamingPolicy2(a) {

        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .create();

        Role role = new Role("Super Administrator");
        String json = gson.toJson(role);
        System.out.println(json);
    }

    /** * Convert field names in json to uppercase letters separated by Spaces * {"Role Name":" super administrator "} */
    @Test
    void setFieldNamingPolicy3(a) {

        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
                .create();

        Role role = new Role("Super Administrator");
        String json = gson.toJson(role);
        System.out.println(json);
    }

    /** * Convert the field names in json to lowercase letters separated by underscores * {"role_name":" super administrator "} */
    @Test
    void setFieldNamingPolicy4(a) {

        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();

        Role role = new Role("Super Administrator");
        String json = gson.toJson(role);
        System.out.println(json);
    }

    /** * Convert the field names in the JSON file to lowercase letters separated by lines * {"role-name":" super administrator "} */
    @Test
    void setFieldNamingPolicy5(a) {

        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
                .create();

        Role role = new Role("Super Administrator");
        String json = gson.toJson(role);
        System.out.println(json);
    }

    /** * Convert the field names in json to lowercase letters in dotted format * {" role-name ":" super administrator "} */
    @Test
    void setFieldNamingPolicy6(a) {

        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS)
                .create();

        Role role = new Role("Super Administrator");
        String json = gson.toJson(role);
        System.out.println(json);
    }

    /** * Property renames * {"menu_name":" system management "} */
    @Test
    void serializedName(a) {
        Menu menu = new Menu("System Management");

        String json = new Gson().toJson(menu);
        System.out.println(json);
    }

    /** * {"dept_name":" dept_name"} */
    @Test
    void adapter(a) {
        Gson gson = new GsonBuilder()
                // Register TypeAdapter for Dept
                .registerTypeAdapter(Dept.class, new DeptAdapter())
                .create();

        Dept dept = new Dept("Product Development Department"); String json = gson.toJson(dept); System.out.println(json); }}Copy the code

FastJson

Maven rely on

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>
Copy the code

Unit testing

public class FastJsonTest {

    / * * * {" roles ": [{" roleName" : "system administrator"}, {" roleName ", "general manager"}], "userName" : "admin"} * /
    @Test
    void toJson(a) {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");
        User user = new User();
        user.setUserName("admin");
        user.setRoles(Arrays.asList(role1, role2));

        String userJson = JSON.toJSONString(user);
        System.out.println(userJson);
    }

    Admin / * * * * {" roles ": [{" roleName" : "system administrator"}, {" roleName ", "general manager"}], "userName" : "admin"} * /
    @Test
    void jsonParse(a) {
        String json = "{\" roles \ ": [{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}], \" the userName \ ": \" admin \ "}";
        JSONObject jsonObject = JSON.parseObject(json);

        System.out.println(jsonObject.getString("userName"));
        System.out.println(jsonObject);
    }

    / * * * [{" roleName ":" system administrator "}, {" roleName ", "general manager"}] * /
    @Test
    void list2Json(a) {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");

        String jsonString = JSON.toJSONString(Arrays.asList(role1, role2));

        System.out.println(jsonString);
    }

    / * * * [{" roleName ":" system administrator "}, {" roleName ", "general manager"}] * /
    @Test
    void json2List(a) {
        String json = "[{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}"]";

        JSONArray jsonArray = JSON.parseArray(json);
        System.out.println(jsonArray);
    }

    /** * [Role(roleName= administrator), Role(roleName= administrator)] */
    @Test
    void json2List2(a) {
        String json = "[{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}"]";

        List<Role> users = JSON.parseArray(json, Role.class);
        System.out.println(users);
    }

    /** * User(userName=admin, roles=[Role(roleName= administrator), Role(roleName= administrator)]) */
    @Test
    void json2Bean(a) {
        String json = "{\" roles \ ": [{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}], \" the userName \ ": \" admin \ "}";

        User user = JSON.parseObject(json, User.class);
        System.out.println(user);
    }

    /** * User(userName=admin, roles=[Role(roleName= administrator), Role(roleName= administrator)]) */
    @Test
    void json2Bean2(a) {
        String json = "{\" roles \ ": [{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}], \" the userName \ ": \" admin \ "}";

        User user = JSON.parseObject(json, new TypeReference<User>(){});
        System.out.println(user);
    }

    /** * {"userName":"admin"} */
    @Test
    void map2Json(a) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userName"."admin");

        String jsonString = JSON.toJSONString(hashMap);
        System.out.println(jsonString);
    }

    /** * admin */
    @Test
    void json2Map(a) {
        String json = "{\"userName\":\"admin\"}";

        Map<String, String> map = (Map<String, String>) JSON.parse(json);
        System.out.println(map.get("userName"));
    }

    /** * {"userName":"admin"} */
    @Test
    void json2Map2(a) {
        String json = "{\"userName\":\"admin\"}";

        Map map = JSON.parseObject(json);
        System.out.println(map);
    }

    / * * * {" groupName ":" group 1 ", "idNumber" : {" 001 ": {" roles" : [{" roleName ":" system administrator "}, {" roleName ", "general manager"}], "userName" : "admin"}}} * /
    @Test
    void obj2Json(a) {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");
        User user = new User();
        user.setUserName("admin");
        user.setRoles(Arrays.asList(role1, role2));

        HashMap<String, User> map = new HashMap<>();
        map.put("001", user);
        UserGroup userGroup = new UserGroup();
        userGroup.setGroupName("Group 1");
        userGroup.setIdNumber(map);

        String jsonString = JSON.toJSONString(userGroup);
        System.out.println(jsonString);
    }

    /** * UserGroup(groupName= group 1, idNumber={001=User(userName=admin, roles=[Role(roleName= system administrator), Role(roleName= normal administrator)])}) */
    @Test
    void json2Obj(a) {
        String json = "{\" groupName \ ": \" group 1 \ "and \" idNumber \ ": {\" 001 \ ": {\" roles \ ": [{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}], \" the userName \ ":\"admin\"}}}"; UserGroup userGroup = JSON.parseObject(json, UserGroup.class); System.out.println(userGroup); }}Copy the code

Jackson

Unit testing

/ * * *@authorWhen I meet you * @public number when I meet you *@sinceThe 2020-06-11 * /
public class JacksonTest {

    / * * * {" userName ":" admin ", "roles" : [{" roleName ":" system administrator "}, {" roleName ", "general manager"}]} *@throws JsonProcessingException
     */
    @Test
    void Obj2Json(a) throws JsonProcessingException {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");
        User user = new User();
        user.setUserName("admin");
        user.setRoles(Arrays.asList(role1, role2));

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);

        System.out.println(json);
    }

    /** * Required no parameter constructor * User(userName=admin, roles=[Role(roleName= system administrator), Role(roleName= common administrator)]) *@throws JsonProcessingException
     */
    @Test
    void json2Obj(a) throws JsonProcessingException {
        String json = "{\ userName \" : \ "admin \", \ "roles \" : [{\ "roleName \" : \ \ "system administrator"}, {\ "roleName \" : \ "general manager \}]}";

        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);
        System.out.println(user);
    }

    /**
     * admin
     * @throws JsonProcessingException
     */
    @Test
    void json2Obj2(a) throws JsonProcessingException {
        String json = "{\ userName \" : \ "admin \", \ "roles \" : [{\ "roleName \" : \ \ "system administrator"}, {\ "roleName \" : \ "general manager \}]}";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);

        String userName = jsonNode.get("userName").asText();
        System.out.println(userName);
    }

    / [* * * {" roleName ":" system administrator "}, {" roleName ", "general manager"}] *@throws JsonProcessingException
     */
    @Test
    void list2Json(a) throws JsonProcessingException {
        Role role1 = new Role("System Administrator");
        Role role2 = new Role("General Administrator");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(Arrays.asList(role1, role2));

        System.out.println(json);
    }

    /** * No parameter constructor is required * [Role(roleName= system administrator), Role(roleName= common administrator)] *@throws JsonProcessingException
     */
    @Test
    void json2List(a) throws JsonProcessingException {
        String json = "[{\" roleName \ ": \ \" system administrator "}, {\ "roleName \" : \ "general manager \}"]";

        ObjectMapper mapper = new ObjectMapper();
        List<Role> roles = mapper.readValue(json, newTypeReference<List<Role>>() { }); System.out.println(roles); }}Copy the code

The last

This article ends, thanks for reading. If you feel good, please pay attention to the public account [when I meet You], your support is the biggest motivation for my writing.