Java Code Examples for com.google.gson.Gson

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/binding/.

Source file: DefaultDataParser.java

  19 
vote

/** 
 * @param serializedData
 * @param type
 * @return
 */
@SuppressWarnings("unchecked") public <T>Object parseAsArrayList(String serializedData,T type){
  ArrayList<T> newArray=new ArrayList<T>();
  Gson gson=new Gson();
  JsonElement json=new JsonParser().parse(serializedData);
  JsonArray array=json.getAsJsonArray();
  Iterator<JsonElement> iterator=array.iterator();
  while (iterator.hasNext()) {
    JsonElement json2=(JsonElement)iterator.next();
    T object=(T)gson.fromJson(json2,(Class<?>)type);
    newArray.add(object);
  }
  return newArray;
}
 

Example 2

From project github-java-sdk, under directory /core/src/main/java/com/github/api/v2/services/impl/.

Source file: NetworkServiceImpl.java

  19 
vote

@Override public NetworkMeta getNetworkMeta(String userName,String repositoryName){
  GitHubApiUrlBuilder builder=createGitHubApiUrlBuilder(GitHubApiUrls.NetworkApiUrls.GET_NETWORK_META_URL);
  String apiUrl=builder.withField(ParameterNames.USER_NAME,userName).withField(ParameterNames.REPOSITORY_NAME,repositoryName).buildUrl();
  JsonObject json=unmarshall(callApiGet(apiUrl));
  Gson gson=getGsonBuilder().setDateFormat("yyyy-MM-dd").create();
  return gson.fromJson(json,NetworkMeta.class);
}
 

Example 3

From project 4308Cirrus, under directory /tendril-domain/src/main/java/edu/colorado/cs/cirrus/domain/util/.

Source file: JSONUtils.java

  18 
vote

public static <T>ArrayList<T> getResponseAsArrayList(ArrayList<String> JSONArrayList,Class<T> classToReturn){
  GsonBuilder builder=new GsonBuilder();
  Gson gson=builder.create();
  ArrayList<T> returnList=new ArrayList<T>();
  for (  String s : JSONArrayList) {
    returnList.add(gson.fromJson(s,classToReturn));
  }
  return returnList;
}
 

Example 4

From project AdServing, under directory /modules/tools/import/src/main/java/net/mad/ads/base/api/importer/.

Source file: Importer.java

  18 
vote

private JsonElement getJsonObject(File jobFile){
  try {
    String jsonContent=FileUtils.readFileToString(jobFile,"UTF-8");
    Gson gson=GSON_BUILDER.create();
    JsonElement element=gson.fromJson(jsonContent,JsonElement.class);
    return element;
  }
 catch (  Exception e) {
    logger.error("",e);
  }
  return null;
}
 

Example 5

From project AmDroid, under directory /AmenLib/src/main/java/com.jaeckel/amenoid/api/.

Source file: AmenServiceImpl.java

  18 
vote

public static String addKeyValueToJSON(Amen amen,Map<String,String> map){
  Gson gson=new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
  JsonElement element=gson.toJsonTree(amen);
  JsonObject object=element.getAsJsonObject();
  for (  Map.Entry<String,String> entry : map.entrySet()) {
    object.addProperty(entry.getKey(),entry.getValue());
  }
  return object.toString();
}
 

Example 6

From project androidquery, under directory /demo/src/com/androidquery/test/async/.

Source file: AjaxLoadingActivity.java

  18 
vote

public void async_transformer(){
  String url="https://graph.facebook.com/205050232863343";
  GsonTransformer t=new GsonTransformer();
  aq.transformer(t).progress(R.id.progress).ajax(url,Profile.class,new AjaxCallback<Profile>(){
    public void callback(    String url,    Profile profile,    AjaxStatus status){
      Gson gson=new Gson();
      showResult("GSON Object:" + gson.toJson(profile),status);
    }
  }
);
}
 

Example 7

From project ATHENA, under directory /components/reports/src/main/java/org/fracturedatlas/athena/reports/serialization/.

Source file: AthenaReportSerializer.java

  18 
vote

@Override public AthenaReport readFrom(java.lang.Class<AthenaReport> type,java.lang.reflect.Type genericType,java.lang.annotation.Annotation[] annotations,MediaType mediaType,MultivaluedMap<java.lang.String,java.lang.String> httpHeaders,java.io.InputStream entityStream){
  Gson gson=JsonUtil.getGson();
  try {
    AthenaReport tran=gson.fromJson(new InputStreamReader(entityStream),AthenaReport.class);
    return tran;
  }
 catch (  JsonParseException e) {
    e.printStackTrace();
    throw e;
  }
}
 

Example 8

From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.

Source file: ResponseMtGox.java

  18 
vote

@Override public void parseCheckBalance(BufferedReader rd){
  Gson gson=new Gson();
  CheckBalance parseObj=new CheckBalance();
  parseObj=gson.fromJson(rd,CheckBalance.class);
  balance=parseObj;
}
 

Example 9

From project egit-github, under directory /org.eclipse.egit.github.core.tests/src/org/eclipse/egit/github/core/tests/.

Source file: RequestErrorTest.java

  18 
vote

/** 
 * Get request error message for JSON that contains error property
 * @throws Exception
 */
@Test public void requestErrorWithErrorField() throws Exception {
  Gson gson=new Gson();
  RequestError error=gson.fromJson("{\"error\":\"not authorized\"}",RequestError.class);
  assertNotNull(error);
  assertEquals("not authorized",error.getMessage());
  assertNull(error.getErrors());
}
 

Example 10

From project google-gson, under directory /src/test/java/com/google/gson/functional/.

Source file: CustomDeserializerTest.java

  18 
vote

public void testJsonTypeFieldBasedDeserialization(){
  String json="{field1:'abc',field2:'def',__type__:'SUB_TYPE1'}";
  Gson gson=new GsonBuilder().registerTypeAdapter(MyBase.class,new JsonDeserializer<MyBase>(){
    public MyBase deserialize(    JsonElement json,    Type pojoType,    JsonDeserializationContext context) throws JsonParseException {
      String type=json.getAsJsonObject().get(MyBase.TYPE_ACCESS).getAsString();
      return context.deserialize(json,SubTypes.valueOf(type).getSubclass());
    }
  }
).create();
  SubType1 target=(SubType1)gson.fromJson(json,MyBase.class);
  assertEquals("abc",target.field1);
}
 

Example 11

From project GraphLab, under directory /src/graphlab/graph/io/.

Source file: GraphJSON.java

  18 
vote

public static String Graph2Json(GraphModel g){
  GraphJSON gs=new GraphJSON();
  gs.init(g);
  Gson gson=new Gson();
  String ret=gson.toJson(gs);
  return ret;
}
 

Example 12

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/guice/.

Source file: AirCastingModule.java

  17 
vote

@Override protected void configure(){
  requestStaticInjection(HttpBuilder.class);
  bind(Gson.class).toProvider(GsonProvider.class).in(Scopes.SINGLETON);
  bind(HttpClient.class).to(DefaultHttpClient.class);
  bind(AirCastingDB.class).toProvider(AirCastingDBProvider.class);
  bind(NoteOverlay.class).toProvider(NoteOverlayProvider.class);
  bind(Geocoder.class).toProvider(GeocoderProvider.class);
  bind(EventBus.class).in(Scopes.SINGLETON);
  bindConstant().annotatedWith(SharedPreferencesName.class).to("pl.llp.aircasting_preferences");
  bind(BluetoothAdapter.class).toProvider(BluetoothAdapterProvider.class);
  bind(TelephonyManager.class).toProvider(new SystemServiceProvider<TelephonyManager>(Context.TELEPHONY_SERVICE));
}
 

Example 13

From project android-joedayz, under directory /Proyectos/ConsumirWS/src/net/ivanvega/ConsumirWS/.

Source file: ConsumirWSActivity.java

  17 
vote

/** 
 * Metodo que recibe una cadena JSON y la convierte en una lista de objetos AndroidOS para despues cargarlos en la lista
 * @param strJson (String) Cadena JSON
 */
private void crearLista(String strJson){
  gson=new Gson();
  Type lstT=new TypeToken<ArrayList<AndroidOS>>(){
  }
.getType();
  ArrayList<AndroidOS> arrListAOS=new ArrayList<AndroidOS>();
  arrListAOS=gson.fromJson(strJson,lstT);
  lsvAndroidOS.setAdapter(new ArrayAdapter<AndroidOS>(getApplication(),android.R.layout.simple_list_item_1,arrListAOS));
}
 

Example 14

From project Android_1, under directory /GsonJsonWebservice/src/com/novoda/activity/.

Source file: JsonRequest.java

  17 
vote

@Override protected void onResume(){
  super.onResume();
  Toast.makeText(this,"Querying droidcon on Twitter",Toast.LENGTH_SHORT).show();
  Reader reader=new InputStreamReader(retrieveStream(url));
  SearchResponse response=new Gson().fromJson(reader,SearchResponse.class);
  List<String> searches=new ArrayList<String>();
  Iterator<Result> i=response.results.iterator();
  while (i.hasNext()) {
    Result res=(Result)i.next();
    searches.add(res.text);
  }
  ListView v=(ListView)findViewById(R.id.list);
  v.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,searches.toArray(new String[searches.size()])));
}
 

Example 15

From project android_8, under directory /src/com/defuzeme/.

Source file: DefuzeMe.java

  17 
vote

@Override public void onCreate(){
  super.onCreate();
  DefuzeMe._handler=new Handler();
  DefuzeMe.Preferences=new Preferences(this);
  DefuzeMe.Events=new Events(this);
  DefuzeMe.Gson=new Gson();
  DefuzeMe.Gui=new Gui();
  DefuzeMe.Communication=new Communication(this);
  DefuzeMe.Network=new Network(this);
}
 

Example 16

From project Betfair-Trickle, under directory /src/main/java/uk/co/onehp/trickle/services/betfair/.

Source file: BetfairServiceImpl.java

  17 
vote

private void sendRequest(Object body){
  if (body.getClass() != LoginReq.class) {
    if (this.sessionService.getGlobalSessionTokenUpdateDateTime().plusSeconds(this.sessionTimeout).isBefore(new LocalDateTime())) {
      login();
    }
  }
  final Map<String,Object> headers=Maps.newHashMap();
  headers.put("requestType",body.getClass().toString());
  this.producerTemplate.sendBodyAndHeaders("jms:betfair",new Gson().toJson(body),headers);
}
 

Example 17

From project ciel-java, under directory /bindings/src/main/java/com/asgow/ciel/rpc/.

Source file: JsonPipeRpc.java

  17 
vote

public JsonPipeRpc(String toWorkerPipeName,String fromWorkerPipeName){
  try {
    this.toWorkerPipe=new DataOutputStream(new FileOutputStream(toWorkerPipeName));
    this.fromWorkerPipe=new DataInputStream(new FileInputStream(fromWorkerPipeName));
  }
 catch (  IOException ioe) {
    throw new RuntimeException(ioe);
  }
  this.gson=new Gson();
  this.jsonParser=new JsonParser();
}
 

Example 18

From project com.cedarsoft.serialization, under directory /test/performance/src/test/java/com/cedarsoft/serialization/test/performance/.

Source file: GsonTest.java

  17 
vote

@Test public void testFileType() throws Exception {
  com.cedarsoft.serialization.test.performance.jaxb.FileType type=new FileType("jpg",new Extension(".","jpg",true),false);
  assertEquals(FILE_TYPE,new Gson().toJson(type));
  com.cedarsoft.serialization.test.performance.jaxb.FileType deserialized=new Gson().fromJson(FILE_TYPE,FileType.class);
  assertEquals("jpg",deserialized.getId());
  assertEquals("jpg",deserialized.getExtension().getExtension());
  assertEquals(".",deserialized.getExtension().getDelimiter());
  assertTrue(deserialized.getExtension().isDefault());
  assertFalse(deserialized.isDependent());
}
 

Example 19

From project com.idega.content, under directory /src/java/com/idega/content/upload/servlet/.

Source file: BlueimpUploadServlet.java

  17 
vote

@Override protected void doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  IWContext iwc=new IWContext(request,response,getServletContext());
  response=iwc.getResponse();
  response.setContentType("application/json");
  PrintWriter responseWriter=response.getWriter();
  String filePath=iwc.getParameter(PARAMETER_UPLOAD_PATH);
  ArrayList<HashMap<String,Object>> responseMapArray=new ArrayList<HashMap<String,Object>>(1);
  IWResourceBundle iwrb=iwc.getIWMainApplication().getBundle(ContentConstants.IW_BUNDLE_IDENTIFIER).getResourceBundle(iwc);
  HashMap<String,Object> fileData=new HashMap<String,Object>();
  if (StringUtil.isEmpty(filePath)) {
    fileData.put("message",iwrb.getLocalizedString("file_path_is_empty","File path is empty"));
    fileData.put("status","Bad Request");
    Gson gson=new Gson();
    String jsonString=gson.toJson(responseMapArray);
    responseWriter.write(jsonString);
    return;
  }
  try {
    IWSlideService iwSlideService=IBOLookup.getServiceInstance(iwc,IWSlideService.class);
    iwSlideService.deleteAsRootUser(filePath);
    fileData.put("message",iwrb.getLocalizedString("file_deleted","File deleted"));
    fileData.put("status","OK");
    Gson gson=new Gson();
    String jsonString=gson.toJson(responseMapArray);
    responseWriter.write(jsonString);
    return;
  }
 catch (  Exception e) {
    log("Failed to delete file '" + filePath + "'",e);
  }
  IWSlideService iwSlideService=IBOLookup.getServiceInstance(iwc,IWSlideService.class);
  iwSlideService.deleteAsRootUser(filePath);
  fileData.put("message",iwrb.getLocalizedString("error","error"));
  fileData.put("status","Internal Server Error");
  Gson gson=new Gson();
  String jsonString=gson.toJson(responseMapArray);
  responseWriter.write(jsonString);
  return;
}
 

Example 20

From project droidgiro-android, under directory /src/se/droidgiro/scanner/.

Source file: CloudClient.java

  17 
vote

/** 
 * Sends a pair request to the server with the specified pin code.
 * @param pin the pin code to use when pairing with other end.
 * @return the hash code to use in further communication, null if requestwas denied.
 * @throws Exception
 */
public static Registration register(String pin) throws Exception {
  DefaultHttpClient client=new DefaultHttpClient();
  URI uri=new URI(REGISTER_URL);
  Log.e(TAG,"" + uri.toString());
  HttpPost post=new HttpPost(uri);
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("pin",pin));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8");
  post.setEntity(entity);
  HttpResponse res=client.execute(post);
  Log.v(TAG,"Post to register returned " + res.getStatusLine().getStatusCode());
  if (res.getStatusLine().getStatusCode() == 200) {
    StringBuilder sb=new StringBuilder();
    BufferedReader reader=new BufferedReader(new InputStreamReader(res.getEntity().getContent(),"UTF-8"));
    Log.v(TAG,"Post to register returned " + sb + " with status "+ res.getStatusLine().getStatusCode());
    Gson gson=new Gson();
    Registration registration=gson.fromJson(reader,Registration.class);
    Log.v(TAG,registration.toString());
    return registration;
  }
 else   if (res.getStatusLine().getStatusCode() == 401) {
    Log.w(TAG,"Unauthorized");
    return new Registration();
  }
 else {
    Log.e(TAG,"Unknown error");
    return new Registration();
  }
}
 

Example 21

From project drools-mas, under directory /drools-mas-util/src/main/java/org/drools/mas/util/.

Source file: MessageContentEncoder.java

  17 
vote

private static Gson getGsonConverter(){
  if (gsonConverter == null) {
    gsonConverter=new Gson();
  }
  return gsonConverter;
}
 

Example 22

From project eclim, under directory /org.eclim.core/java/org/eclim/plugin/core/preference/.

Source file: Preferences.java

  17 
vote

/** 
 * Gets the array value of a project option/preference.
 * @param project The project.
 * @param name The name of the option/preference.
 * @return The array value or and empty array if not found.
 */
public String[] getArrayValue(IProject project,String name) throws Exception {
  String value=getValues(project).get(name);
  if (value != null && value.trim().length() != 0) {
    return new Gson().fromJson(value,String[].class);
  }
  return ArrayUtils.EMPTY_STRING_ARRAY;
}
 

Example 23

From project groovejaar, under directory /src/jgroove/.

Source file: JGroove.java

  17 
vote

/** 
 * Returns the needed Grooveshark's communication Token value to communicate with the services, it is also stored as attribute to be used by the other methods. It will automatically call getSecretKey().
 * @return Token's value
 * @throws NoSuchAlgorithmException
 * @throws MalformedURLException
 * @throws IOException
 */
public static String getToken() throws IOException {
  HashMap<String,Object> parameters=new HashMap<String,Object>();
  parameters.put("secretKey",JGroove.getSecretKey());
  parameters.put("country",jgroove.json.JsonPost.country);
  JGroove.methodurl="https" + "://" + JGroove.domain + "/"+ JGroove.methodphp;
  String response=JGroove.callMethod(parameters,"getCommunicationToken");
  JGroove.methodurl="http" + "://" + JGroove.domain + "/"+ JGroove.methodphp;
  JGroove.token=(new Gson().fromJson(response,JsonToken.class).result);
  return JGroove.token;
}
 

Example 24

From project CyborgFactoids, under directory /src/main/java/com/alta189/cyborg/factoids/util/.

Source file: HTTPUtil.java

  16 
vote

public static String hastebin(String data){
  HttpClient client=new DefaultHttpClient();
  HttpPost post=new HttpPost(hastebin);
  try {
    post.setEntity(new StringEntity(data));
    HttpResponse response=client.execute(post);
    String result=EntityUtils.toString(response.getEntity());
    return "http://hastebin.com/" + new Gson().fromJson(result,Hastebin.class).getKey();
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 25

From project flatpack-java, under directory /jersey/src/main/java/com/getperka/flatpack/jersey/.

Source file: ApiDescriber.java

  16 
vote

/** 
 * Load the  {@code package.json} file from the class's package.
 */
private Map<String,String> getDocStrings(Class<?> clazz) throws IOException {
  Map<String,String> toReturn=docStringsByPackage.get(clazz.getPackage());
  if (toReturn != null) {
    return toReturn;
  }
  InputStream stream=clazz.getResourceAsStream("package.json");
  if (stream == null) {
    toReturn=Collections.emptyMap();
  }
 else {
    Reader reader=new InputStreamReader(stream,FlatPackTypes.UTF8);
    toReturn=new Gson().fromJson(reader,new TypeReference<Map<String,String>>(){
    }
.getType());
    reader.close();
  }
  docStringsByPackage.put(clazz.getPackage(),toReturn);
  return toReturn;
}
 

Example 26

From project gitblit, under directory /src/com/gitblit/.

Source file: RedmineUserService.java

  16 
vote

@Override public UserModel authenticate(String username,char[] password){
  String urlText=this.settings.getString(Keys.realm.redmine.url,"");
  if (!urlText.endsWith("/")) {
    urlText.concat("/");
  }
  String apiKey=String.valueOf(password);
  try {
    String jsonString=getCurrentUserAsJson(urlText,apiKey);
    RedmineCurrent current=new Gson().fromJson(jsonString,RedmineCurrent.class);
    String login=current.user.login;
    boolean canAdmin=true;
    if (StringUtils.isEmpty(login)) {
      canAdmin=false;
      login=current.user.mail;
    }
    UserModel userModel=new UserModel(login);
    userModel.canAdmin=canAdmin;
    userModel.displayName=current.user.firstname + " " + current.user.lastname;
    userModel.emailAddress=current.user.mail;
    userModel.cookie=StringUtils.getSHA1(userModel.username + new String(password));
    return userModel;
  }
 catch (  IOException e) {
    logger.error("authenticate",e);
  }
  return null;
}