How to serialize an Object to Map by Moshi

Nano Java8 picture Nano Java8 · Nov 2, 2017 · Viewed 11k times · Source

I want to serialize an Object to Map by Moshi.Here is my codes by Gson

    public static Map<String, String> toMap(Object obj, Gson gson) {
    if (gson == null) {
        gson = new Gson();
    }
    String json = gson.toJson(obj);
    Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());
    return map;
}

And how to write by Moshi ?

Answer

Eric Cochran picture Eric Cochran · Nov 3, 2017

Here's one way. Check out the toJsonValue doc here.

Moshi moshi = new Moshi.Builder().build();

JsonAdapter<Object> adapter = moshi.adapter(Object.class);

Object jsonStructure = adapter.toJsonValue(obj);
Map<String, Object> jsonObject = (Map<String, Object>) jsonStructure;

If you know the type of obj, it'd be better to look up the adapter of that type, rather than of Object. (The Object JsonAdadpter has to look up the runtime type on every toJson call.