Processing JSON 2 with Java

Processing JSON 2 with Java

In the last article Processing JSON 1 with Java In JSON, the most original method of parsing JSON is proposed, that is, to process JSON objects and JSON arrays manually through JsonObject classes and JsonArray classes. This method needs to parse every element (object or array) of the whole JSON manually.

In the process of practical application, JSON processing, in addition to simply output through strings, will also need to convert a JSON data into a JAVA object, which involves the so-called serialization and deserialization process.

Define data classes

Since in order to convert JSON to Java objects, the Java object must have a field corresponding to JSON one-to-one class, the third party recommended on Gson's official website Gson Tutorial Series Examples in the tutorial

public class UserSimple {  
    String name;
    String email;
    int age;
    boolean isDeveloper;
}

The corresponding JSON is:

{
  "name": "Norman",
  "email": "norman@futurestud.io",
  "age": 26,
  "isDeveloper": true
}

The code for the conversion between the two is as follows:

Gson gson = new Gson();  

/* from Java Object -> JSON */
String userJson = gson.toJson(userObject);   

/* from JSON to Java Object */
UserSimple userObject = gson.fromJson(userJson, UserSimple.class)

Advanced Play of Custom Serializer and Deserializer

  • When using Gson, you can customize the process of serialization and deserialization by implementing JsonSerializer < T > and JsonDeserializer < T > interfaces.
  • After the JsonSerializer < T > and JsonDeserializer < T > interfaces are implemented, the Override serialize () method and deserialize() method must be rewritten.
  • Each data field of user data can be obtained by Java Field class, which can be used to determine whether Json contains the value of the field.
  • For a custom serialization or deserialization process to take effect, you need to call the registerTypeAdapter() method when instantiating objects of the Gson class

Taking the custom deserialization process as an example, the key code is as follows:

/* Instantiate Gson objects and register custom deserialization processes */
Gson gson = new GsonBuilder()
                .registerTypeAdapter(UserSimple.class, new UserSimpleDeserializer())
                .create();

/* Implementation of a custom deserializer for Json Deserializer interface */
public class UserSimpleDeserializer implements JsonDeserializer<WifiData> {

    public UserSimple deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jsonObject = (JsonObject) jsonElement;

        Field[] fields = UserSimple.class.getDeclaredFields();    // Get all data domains of user data classes
        for (Field field : fields) {
            String fieldName = field.getName();
            doProcess();
        }

        return new Gson().fromJson(jsonElement, UserSimple.class);
    } 
}   

Higher-order play of custom key s when outputting Json

When a Java object is serialized into a Json string, the key name of each JsonObject is determined by the domain name of the data domain of the Java object class. To control the key name in the output process, the FieldNaming Strategy interface can be implemented.

  • To implement a custom domain name strategy for the FieldNaming Strategy interface, the translateName() method must be rewritten
  • To make the custom domain name policy work, you need to call the setFieldNamingStrategy() method when instantiating objects of the Gson class
/* Instantiate Gson objects and set custom naming policies */
Gson gson = new GsonBuilder()
                .setFieldNamingStrategy(new UserSimpleNamingStrategy())
                .create();

public class WifiDataNamingStrategy implements FieldNamingStrategy {
    public String translateName(Field field) {
        if (field.getName().equals("someName")) {
            return "newName";
        } 
        return field.getName();
    }
}    

Keywords: JSON Java

Added by anon on Mon, 15 Jul 2019 22:36:10 +0300