0

I wanna build a Class to parse List<T> to/from String using Gson:

private static class ListParser<T> {

    Gson gson = new Gson();

    public Type getGenericClass() {
        Type listType = new TypeToken<List<T>>() {
        }.getType();
        return listType;
    }

    public String toJson(List<T> list) {
        return gson.toJson(list, getGenericClass());
    }

    public List<T> fromJson(String json) {
        List<T> list1 = gson.fromJson(json, getGenericClass());
        List<T> list2 = new ArrayList<T>();
        for (int i = 0; i < list1.size(); i++) {
            T val = (T) list1.get(i);
            list2.add(val);
        }
        return list2;
    }
}

I used TypeToken as some tutorial I've found, but list1 and list2 were all List<Double>. I wonder if there is anyway to parse List<Double> to List<T> in Java.


How to check if a property of an Entity Framework type is Nullable

I have a EntityDataModel generated from my database. One of the Entity models has two properties that are both string types. One is Nullable=True and the other Nullable=False

How do I check the value of the Nullable property during runtime ?

4

1 回答 1

0

getGenericClass()不会工作,你需要检索 T 的类。

你可以提供它:

  Class<T> type;

  public Class<T> getType() {
    return this.type;
  }

或者在运行时获取它(不安全,我认为你可以在这个 subjet 上找到很多帖子)

  public Class<T> getType() {
    return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
  }

然后要构建列表令牌,您可以使用以下代码:

  static TypeToken<?> getGenToken(final Class<?> raw, final Class<?> gen) throws Exception {
    Constructor<ParameterizedTypeImpl> constr = ParameterizedTypeImpl.class.getDeclaredConstructor(Class.class, Type[].class, Type.class);
    constr.setAccessible(true);
    ParameterizedTypeImpl paramType = constr.newInstance(raw, new Type[] { gen }, null);

    return TypeToken.get(paramType);
  }

检查我在此处提供的示例:GSON 反序列化复杂对象数组

于 2013-09-13T12:52:10.507 回答