Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize an Object to Map by Moshi

Tags:

moshi

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 ?

like image 782
Nano Java8 Avatar asked Nov 01 '25 11:11

Nano Java8


2 Answers

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.

like image 126
Eric Cochran Avatar answered Nov 04 '25 20:11

Eric Cochran


@NanoJava8 solution crashes but can be made to work with a minor change using Map instead of HashMap

Type type = Types.newParameterizedType(Map.class, String.class, String.class);

JsonAdapter<Map<String,String>> adapter = moshi.adapter(type);

Map<String,String> map = adapter.fromJson(json);

As stated by Jesse in the answer Moshi support fields as Map but not HashMap.

like image 26
farhan patel Avatar answered Nov 04 '25 18:11

farhan patel