Search code examples
javaandroidjsonmoshi

TypeParameter as an Expression argument


I wanted to create a helper class that will help me serialize any object to json and vice versa. I tried to google but nothing relevant. Maybe I do not know what is the correct term to search for. Here's what I have worked on so far..

public class Serializer {
private static Moshi moshi;

public Serializer(){
    moshi = new Moshi.Builder().build();
}

public static <T> T parse(String json) throws IOException {
    JsonAdapter<T> adapter = moshi.adapter(T); 
    // error at adapter(T): "Expression expected"
    return adapter.fromJson(json);
}

@NonNull
public static <T> String stringify(T obj){
    JsonAdapter<T> adapter = moshi.adapter(T); 
    // same error as the above 
    return adapter.toJson(obj);
}
}

If what I am trying to do is useless, do I have to make toJson() and fromJson on each of my classes?


Solution

  • You need to provide a class object to the moshi.adapter() method:

    public final class Serializer {
        private static Moshi moshi = new Moshi.Builder().build();
    
        public static <T> T parse(String json, Class<T> objClass) throws IOException {
            JsonAdapter<T> adapter = moshi.adapter(objClass); 
            return adapter.fromJson(json);
        }
    
        @NonNull
        public static <T> String stringify(T obj, Class<T> objClass) {
            JsonAdapter<T> adapter = moshi.adapter(objClass); 
            return adapter.toJson(obj);
        }
    }