0
votes

Given the class:

class Container<T> {
 T item;
 String type;
 Map<String,String> properties;

 public void setItem(T _item) {
  item = _item;
 }
}

I have already the item serialized in a database as string with the name serialized. It is a Map<String,String>. I don't know how to say Gson that this variable is already serialized. So when I use Gson I first deserialize it, then serialize it back

Container<Map <String, String>> t = new Container<>(<other parameters>);
Map <String, String> m = gson.fromJson(serialized, new TypeToken<Map<String,String>>(){}.getType())
t.setItem(m);
gson.toJson(t,  new TypeToken<Container<Map<String,String>>>() {}.getType());

This feels inefficient. How do I fix this?

1

1 Answers

0
votes

I'm not sure that's possible. You're mixing object creation and serialization.

What you can do is create a new constructor with an additional String parameter and deserialize the string to get your item and set it automatically. That should be possible even with a parameterized type. That way you have 2 lines of code instead of 4.