Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

There are several ways in which Gson can serialize a Map object without ignoring the output of certain fields. However, in our example, the objects that need to be serialized are Java Bean objects.

Let’s use the actual case to demonstrate how to implement the Map to ignore the specified key function

The main knowledge point used here is the extended TypeAdapter provided by Gson. Through the self-defined adapter, the self-defined serialization/deserialization can be realized. The logic we need to achieve is as follows

public static class IgnoreMapTypeAdapter extends TypeAdapter<HashMap> {

    @Override
    public void write(JsonWriter out, HashMap value) throws IOException {
        Set<Map.Entry<Object, Object>> set = value.entrySet();
        out.beginObject();
        for (Map.Entry<Object, Object> entry : set) {
            // Ignore key = kv of PWD when serializing output
            String strKey = String.valueOf(entry.getKey());
            if (strKey.equalsIgnoreCase("pwd")) {
                continue;
            }
            out.name(strKey);
            Object v = entry.getValue();
            if (v instanceof String) {
                out.value((String) v);
            } else if (v instanceof Number) {
                out.value((Number) v);
            } else if (v instanceof Boolean) {
                out.value((Boolean) v);
            } else {
                out.value(getGson().toJson(entry.getValue()));
            }
        }
        out.endObject();
    }

    @Override
    public HashMap read(JsonReader in) throws IOException {
    	// The standard gson deserialization is used directly here
        Gson gson = new Gson();
        returngson.fromJson(in, HashMap.class); }}Copy the code

Note the write method in the implementation logic above, traversing the map, where all keys are treated as strings by default. The internal implementation is mainly based on Gson’s streaming serialization strategy (JsonWrite streaming serialization, next post).

Secondly, for the output of value, simple adaptation is made here. If it is not a basic type, ordinary Gson is not used for conversion, but a recursive approach is adopted. The key point is the implementation logic of etGson()

private static Gson getGson(a) {
    return new GsonBuilder().registerTypeAdapter(HashMap.class, new IgnoreMapTypeAdapter()).create();
}
Copy the code

So let’s write a simple case to verify that

private static Map<String, Object> newMap(String key, Object val, Object... kv) {
    Map<String, Object> ans = new HashMap<>(8);
    ans.put(key, val);
    for (int i = 0, size = kv.length; i < size; i += 2) {
        ans.put(String.valueOf(kv[i]), kv[i + 1]);
    }
    return ans;
}


@Test
public void testCase(a) {
    Gson gson = getGson();

    Map map = newMap("user"."yihui"."pwd".123455."sub", newMap("key"."lll"."v".1234L."pwd"."abc"), "list", Arrays.asList(1.2.3));
    String str = gson.toJson(map);
    System.out.println(str);
    System.out.println(new Gson().toJson(map));
}
Copy the code

The output is as follows

{"sub":"{\"key\":\"lll\",\"v\":1234}"."list":"[1, 2, 3]"."user":"yihui"}
{"sub": {"pwd":"abc"."key":"lll"."v": 1234}."pwd": 123455,"list": [1, 2, 3],"user":"yihui"}
Copy the code

Notice that the first line ignores the PWD json string and the second line is the normal Gson output JSON string. Although the first one satisfied our requirements, the value of sub changed from Object to String, which is not quite what we expected. Next, streaming serialization will bring a solution in the next blog post

A gray contact information

All letter is better than no book, the above content, purely one’s words, due to the limited personal ability, it is hard to avoid omissions and mistakes, such as finding bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Personal site: blog.hhui.top
  • Micro Blog address: Small Gray Blog
  • QQ: a gray /3302797840
  • Wechat official account: One Grey Blog