Gson turn an array of data objects into json - Android

前端 未结 2 1130
旧巷少年郎
旧巷少年郎 2020-12-02 18:31

Currently I am working on a native android app with webView front end.

I have something like:

public class dataObject
{
  int a;
  String b;
}
         


        
2条回答
  •  攒了一身酷
    2020-12-02 18:56

    My version of gson list deserialization using a helper class:

    public List getList(Class type, JSONArray json) throws Exception {
        Gson gsonB = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    
        return gsonB.fromJson(json.toString(), new JsonListHelper(type));
    }
    
    
    
    public class JsonListHelper implements ParameterizedType {
    
      private Class wrapped;
    
      public JsonListHelper(Class wrapped) {
        this.wrapped = wrapped;
      }
    
      public Type[] getActualTypeArguments() {
        return new Type[] {wrapped};
      }
    
      public Type getRawType() {
        return List.class;
      }
    
      public Type getOwnerType() {
        return null;
      }
    
    }
    

    Usage

    List objects = getList(Object.class, myJsonArray);
    
        

    提交回复
    热议问题