Skip to content

Instantly share code, notes, and snippets.

@TarekkMA
Last active May 12, 2016 08:29
Show Gist options
  • Save TarekkMA/567a9b84f6f6314c84206256180358f0 to your computer and use it in GitHub Desktop.
Save TarekkMA/567a9b84f6f6314c84206256180358f0 to your computer and use it in GitHub Desktop.
import com.google.gson.Gson;
import java.util.Arrays;
import java.util.List;
/**
* Created by TarekkMA on 5/10/16.
* www.FaceBook.com/tarekkma1
*/
public class JsonHelper {
private static final String TAG = "JsonHelper";
/**
* Convert any object to json string
* @param o The object you wish to convert
* @return String containing the converted json
*/
public static String objectToJson(Object o){
return new Gson().toJson(o);
}
/**
* Method to convert json to any object using generics
* @param json The json string you wish to convert
* @param clazz class of the object you desire
* @return The object that you passed its class
*/
public static <T> T jsonToObject(String json,Class<T> clazz){
return new Gson().fromJson(json, clazz);
}
/**
* Method to convert json to list of any object using generics
* @param json The json string you wish to convert
* @param clazz Array class of the object you desire
* @return List of the object you pass its array class
*/
public static <T> List<T> jsonToList(String json,Class<T[]> clazz){
T[] array = new Gson().fromJson(json, clazz);
return Arrays.asList(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment