Example #1
1
  public UserListBean getUserList() throws WeiboException {

    String url = WeiBoURLs.USERS_SEARCH;

    Map<String, String> map = new HashMap<String, String>();
    map.put("access_token", access_token);
    map.put("count", count);
    map.put("page", page);
    map.put("q", q);

    String jsonData = null;

    jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);

    Gson gson = new Gson();

    UserListBean value = null;
    try {
      value = gson.fromJson(jsonData, UserListBean.class);
    } catch (JsonSyntaxException e) {

      AppLoggerUtils.e(e.getMessage());
    }

    return value;
  }
 @Override
 protected void onPostExecute(String result) {
   if (null != dialog) {
     dialog.dismiss();
   }
   if (result == null || result.equals("")) {
     ToastUtils.showToast(mContext, "列表为空");
   } else {
     if (followOrUnfollowModelList != null && !followOrUnfollowModelList.equals("")) {
       followOrUnfollowModelList = new String();
       //					Toast.makeText(getApplicationContext(), "操作失败", 1).show();
     } else followOrUnfollowModelList = new String();
     try {
       followOrUnfollowModelList = new UserCenterParse().parseFollowOrUnfollowResponse(result);
       System.out.println("followOrUnfollowModelList: " + followOrUnfollowModelList);
       if (followed.equals("0")) {
         Toast.makeText(getApplicationContext(), "关注成功", 1).show();
         followed = "1";
       } else if (followed.equals("1")) {
         Toast.makeText(getApplicationContext(), "取消关注成功", 1).show();
         followed = "0";
       }
       new GetUserInformaitonById(UserInformationActivity.this, 1).execute("");
     } catch (JsonSyntaxException e) {
       e.printStackTrace();
     }
   }
 }
Example #3
0
  public List<String> getInfo() throws WeiboException {

    String url = WeiBoURLs.GROUP_MEMBER_LIST;

    Map<String, String> map = new HashMap<String, String>();
    map.put("access_token", access_token);
    map.put("uids", uids);

    String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);

    Gson gson = new Gson();

    List<GroupUser> value = null;
    try {
      value = gson.fromJson(jsonData, new TypeToken<List<GroupUser>>() {}.getType());
    } catch (JsonSyntaxException e) {
      AppLoggerUtils.e(e.getMessage());
    }

    if (value != null && value.size() > 0) {
      GroupUser user = value.get(0);
      List<String> ids = new ArrayList<String>();
      for (GroupBean b : user.lists) {
        ids.add(b.getIdstr());
      }
      return ids;
    }

    return null;
  }
  public MessageListBean getGSONMsgList() {

    String json = getMsgListJson();
    Gson gson = new Gson();

    MessageListBean value = null;

    try {
      value = gson.fromJson(json, MessageListBean.class);
    } catch (JsonSyntaxException e) {
      ActivityUtils.showTips("发生错误,请重刷");
      AppLogger.e(e.getMessage().toString());
    }

    if (value != null) {
      List<WeiboMsgBean> msgList = value.getStatuses();

      Iterator<WeiboMsgBean> iterator = msgList.iterator();

      while (iterator.hasNext()) {

        WeiboMsgBean msg = iterator.next();
        if (msg.getUser() == null) {
          iterator.remove();
        }
      }
    }
    return value;
  }
  public GetStreamKeyStreamServer getGetStreamKeyStreamServer(
      String songID, GetCountry country, String sesionID) {
    GetStreamKeyStreamServer res = null;
    String post =
        "{\"method\":\"getStreamKeyStreamServer\",\"header\":{\"wsKey\":\""
            + KEY
            + "\",\"sessionID\":\""
            + sesionID
            + "\"},\"parameters\":{\"songID\":\""
            + songID
            + "\",\"country\":"
            + country.getResult()
            + ",\"lowBitrate\":\"\"}}";
    ClientResource cr = new ClientResource(uri + getSignatures(post));
    try {
      res = gson.fromJson(cr.post(post).getText(), GetStreamKeyStreamServer.class);
    } catch (JsonSyntaxException e) {
      e.printStackTrace();
    } catch (ResourceException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return res;
  }
Example #6
0
  public static void main(String[] args) {

    JsonParser parser = new JsonParser();
    try {

      JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));

      System.out.println("cat=" + object.get("cat").getAsString());
      System.out.println("pop=" + object.get("cat").getAsBoolean());

      JsonArray array = object.get("languages").getAsJsonArray();

      for (int i = 0; i < array.size(); i++) {

        System.out.println("----------------------");

        JsonObject subObject = array.get(i).getAsJsonObject();

        System.out.println("id=" + subObject.get("id").getAsInt());
        System.out.println("name=" + subObject.get("name").getAsString());
        System.out.println("ide=" + subObject.get("ide").getAsString());
      }

    } catch (JsonIOException e) {
      e.printStackTrace();
    } catch (JsonSyntaxException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Example #7
0
  /**
   * lets an instance of Spawner spawn testlevel.json and checks whether the specified Moveables
   * have been created and are in the right position.
   */
  public void testSpawning() {

    GS.enemys = new Vector<Moveable>();
    GS.friendlys = new Vector<Moveable>();
    ;
    initGL();
    GS.deltaUpdater = new DeltaUpdater();
    Spawner s = new Spawner("testlevel", GS.deltaUpdater);
    s.update(400);
    Vector<Observer> observers = null;
    try {
      Field observerField = DeltaUpdater.class.getDeclaredField("observers");
      observerField.setAccessible(true);
      observers = (Vector<Observer>) observerField.get(GS.deltaUpdater);
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchFieldException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Gson g = new Gson();
    HashMap<BigDecimal, Spawn[]> LevelMap = null;
    try {
      LevelMap =
          g.fromJson(
              new FileReader("json/level/testlevel.json"),
              (new TypeToken<HashMap<BigDecimal, Spawn[]>>() {}).getType());
    } catch (JsonIOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonSyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Spawn[] SpawnArray = LevelMap.get(LevelMap.keySet().toArray()[0]);
    assertTrue(observers.size() == SpawnArray.length + 1);
    // +1 weil Spawner selbst registriert ist
    for (int i = 0; i < observers.size() - 1; ++i) {
      assertTrue(
          ((Entity) observers.get(i + 1)).getClass().getName().equals(SpawnArray[i].Moveable));
      assertTrue(((Entity) observers.get(i + 1)).posX == SpawnArray[i].x);
      assertTrue(((Entity) observers.get(i + 1)).posY == SpawnArray[i].y);
      // assertTrue(((Entity)observers.get(i)).posX == al.get(i).x);

    }
  }
 /** 把Json格式的字符串转换成实体类型的方法. 注意:实体类中的变量需要用@SerializedName注释 */
 public final <T> T get(String value, Class<T> classOfT) {
   try {
     Gson gson =
         new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
     return gson.fromJson(value, classOfT);
   } catch (JsonSyntaxException exception) {
     Log.d("JsonSyntaxException", exception.getMessage());
   }
   return null;
 }
Example #9
0
  private static String[] deserializeJson(final String value) {
    log.debug("Deserialization JSON data");

    try {
      return new Gson().fromJson(value, String[].class);
    } catch (final JsonSyntaxException e) {
      log.warn("Deserialization error, using string as is: {}", e.getMessage());
      return new String[] {value};
    }
  }
  public static WrappedStack createFromJson(String jsonWrappedObject) throws JsonParseException {
    try {
      return gsonSerializer.fromJson(jsonWrappedObject, WrappedStack.class);
    } catch (JsonSyntaxException exception) {
      LogHelper.severe(exception.getMessage());
    } catch (JsonParseException exception) {
      LogHelper.severe(exception.getMessage());
    }

    return null;
  }
Example #11
0
  /**
   * example: Type type = new TypeToken<ArrayList<String>>() {}.getType(); orgList = new
   * Gson().fromJson(rtnOrgStr, type);
   *
   * @param json
   * @param type
   * @param <T>
   * @return
   */
  public static <T> T unserializeJson(String json, Type type) {

    Gson mapper = new Gson();

    try {
      return (T) mapper.fromJson(json, type);
    } catch (JsonSyntaxException e) {
      e.printStackTrace();
      throw new RuntimeException("JSON Unserialize Error");
    }
  }
  public static WrappedStack createFromJson(String jsonWrappedObject) throws JsonParseException {
    try {
      return jsonSerializer.fromJson(jsonWrappedObject, WrappedStack.class);
    } catch (JsonSyntaxException exception) {
      exception.printStackTrace();
    } catch (JsonParseException exception) {
      exception.printStackTrace();
    }

    return null;
  }
  /**
   * Deserializes an EmcValue object from the given serialized json String
   *
   * @param jsonEnergyValue Json encoded String representing a EmcValue object
   * @return The EmcValue that was encoded as json, or null if a valid EmcValue could not be decoded
   *     from given String
   */
  @SuppressWarnings("unused")
  public static EnergyValue createFromJson(String jsonEnergyValue) {
    try {
      return jsonSerializer.fromJson(jsonEnergyValue, EnergyValue.class);
    } catch (JsonSyntaxException exception) {
      exception.printStackTrace();
    } catch (JsonParseException exception) {
      exception.printStackTrace();
    }

    return null;
  }
Example #14
0
  /**
   * Called by the Android system in response to a request to run the sync adapter. The work
   * required to read data from the network, parse it, and store it in the content provider is done
   * here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter run on
   * a background thread. For this reason, blocking I/O and other long-running tasks can be run
   * <em>in situ</em>, and you don't have to set up a separate thread for them. .
   *
   * <p>This is where we actually perform any work required to perform a sync. {@link
   * AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread, so it is
   * safe to peform blocking I/O here.
   *
   * <p>The syncResult argument allows you to pass information back to the method that triggered the
   * sync.
   */
  @Override
  public void onPerformSync(
      Account account,
      Bundle extras,
      String authority,
      ContentProviderClient provider,
      SyncResult syncResult) {
    Log.i(TAG, "Beginning network synchronization");
    try {
      final URL location = new URL(POPULAR_MOVIE_URL);
      InputStream stream = null;

      try {
        Log.i(TAG, "Streaming data from network: " + location);
        stream = downloadUrl(location);
        updateMovieDetails(stream, syncResult);

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
      } catch (JsonSyntaxException jse) {
        jse.printStackTrace();
      } finally {
        if (stream != null) {
          stream.close();
        }
      }
    } catch (MalformedURLException e) {
      Log.wtf(TAG, "Feed URL is malformed", e);
      syncResult.stats.numParseExceptions++;
      return;
    } catch (IOException e) {
      Log.e(TAG, "Error reading from network: " + e.toString());
      syncResult.stats.numIoExceptions++;
      return;
    } catch (XmlPullParserException e) {
      Log.e(TAG, "Error parsing feed: " + e.toString());
      syncResult.stats.numParseExceptions++;
      return;
    } catch (ParseException e) {
      Log.e(TAG, "Error parsing feed: " + e.toString());
      syncResult.stats.numParseExceptions++;
      return;
    } catch (RemoteException e) {
      Log.e(TAG, "Error updating database: " + e.toString());
      syncResult.databaseError = true;
      return;
    } catch (OperationApplicationException e) {
      Log.e(TAG, "Error updating database: " + e.toString());
      syncResult.databaseError = true;
      return;
    }
    Log.i(TAG, "Network synchronization complete");
  }
 protected List<CardData> loadRawData() {
   try {
     return gson.fromJson(readLibrarySource(), getType());
   } catch (JsonIOException e) {
     e.printStackTrace();
   } catch (JsonSyntaxException e) {
     e.printStackTrace();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   return Collections.emptyList();
 }
Example #16
0
  public List<MessageReCmtCountBean> get() throws WeiboException {

    String json = getJson();

    List<MessageReCmtCountBean> value = null;
    try {
      value = new Gson().fromJson(json, new TypeToken<List<MessageReCmtCountBean>>() {}.getType());
    } catch (JsonSyntaxException e) {

      AppLogger.e(e.getMessage());
    }

    return value;
  }
 Object throwExceptions(Type type, String jsonFile) {
   try {
     Gson gson = new Gson();
     Thread.sleep(2000);
     return gson.fromJson(readFileFromAssets(jsonFile, context), type);
   } catch (JsonSyntaxException e) {
     Log.e(ERROR_API, jsonFile + " contains a syntax error " + e.getMessage());
   } catch (IOException e) {
     Log.e(ERROR_API, jsonFile + " could not be found");
   } catch (InterruptedException e) {
     Log.e(ERROR_API, e.getMessage());
   }
   return new Object();
 }
Example #18
0
 protected void process(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   response.setContentType("application/json");
   response.setCharacterEncoding("UTF-8");
   response.setStatus(200);
   JsonObject res;
   try {
     res = getResponse(request);
     response.getWriter().print(res);
     response.getWriter().close();
   } catch (JsonSyntaxException e) {
     throw new GridException(e.getMessage());
   }
 }
  /**
   * Parse a JSON {@link String} to build the {@link Object} of {@link Class} specified from {@value
   * c}.
   *
   * @param jsonString the {@link String} to parse.
   * @param c the {@link Class}'s {@link Object} to build.
   * @return
   */
  public static Object parseJson(String jsonString, Class<?> c) {
    Object result = null;
    long start = System.currentTimeMillis();
    if (manager == null) {
      manager = new JsonManager();
    }
    try {
      result = gson.fromJson(jsonString, c);
    } catch (JsonSyntaxException e) {
      e.printStackTrace();
    }

    long finish = System.currentTimeMillis();
    System.out.println("Elapsed time: " + (finish - start));
    return result;
  }
 public GetCountry getCountry() {
   GetCountry res = null;
   String post =
       "{\"method\":\"getCountry\",\"header\":{\"wsKey\":\"" + KEY + "\"},\"parameters\":[]}";
   ClientResource cr = new ClientResource(uri + getSignatures(post));
   try {
     res = gson.fromJson(cr.post(post).getText(), GetCountry.class);
   } catch (JsonSyntaxException e) {
     e.printStackTrace();
   } catch (ResourceException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return res;
 }
Example #21
0
 private UserCacheRecord read(StorageKey key) throws LocalDBException {
   final String jsonValue = localDB.get(DB, key.getKey());
   if (jsonValue != null && !jsonValue.isEmpty()) {
     try {
       return JsonUtil.deserialize(jsonValue, UserCacheRecord.class);
     } catch (JsonSyntaxException e) {
       LOGGER.error(
           "error reading record from cache store for key="
               + key.getKey()
               + ", error: "
               + e.getMessage());
       localDB.remove(DB, key.getKey());
     }
   }
   return null;
 }
 public StartSession getStartSession() {
   StartSession res = null;
   String post =
       "{\"method\":\"startSession\",\"header\":{\"wsKey\":\"" + KEY + "\"},\"parameters\":[]}";
   String sig = getSignatures(post);
   ClientResource cr = new ClientResource(uri + sig);
   try {
     res = gson.fromJson(cr.post(post).getText(), StartSession.class);
   } catch (JsonSyntaxException e) {
     e.printStackTrace();
   } catch (ResourceException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return res;
 }
Example #23
0
  public boolean destroy() throws WeiboException {
    String url = URLHelper.STATUSES_DESTROY;
    Map<String, String> map = new HashMap<String, String>();
    map.put("access_token", access_token);
    map.put("id", id);

    String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Post, url, map);
    Gson gson = new Gson();

    try {
      MessageBean value = gson.fromJson(jsonData, MessageBean.class);
    } catch (JsonSyntaxException e) {
      AppLogger.e(e.getMessage());
      return false;
    }

    return true;
  }
Example #24
0
 public static <R> R parseJson(okhttp3.Response response, Type bodyType)
     throws HasuraJsonException {
   int code = response.code();
   try {
     String rawBody = response.body().string();
     System.out.println(rawBody);
     return gson.fromJson(rawBody, bodyType);
   } catch (JsonSyntaxException e) {
     String msg =
         "FATAL : JSON strucutre not as expected. Schema changed maybe? : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   } catch (JsonParseException e) {
     String msg = "FATAL : Server didn't return vaild JSON : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   } catch (IOException e) {
     String msg = "FATAL : Decoding response body failed : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   }
 }
  public MessageListBean getGSONMsgList() throws WeiboException {

    String json = getMsgListJson();
    Gson gson = new Gson();

    MessageListBean value = null;
    try {
      value = gson.fromJson(json, MessageListBean.class);
    } catch (JsonSyntaxException e) {

      AppLogger.e(e.getMessage());
      return null;
    }
    if (value != null && value.getItemList().size() > 0) {
      TimeLineUtility.filterMessage(value);
    }

    return value;
  }
    @Override
    protected void onPostExecute(String result) {
      if (null != dialog) {
        dialog.dismiss();
      }
      Log.d("onPostExecute", "postExec state");
      if (result == null || result.equals("")) {
        // show empty alert
      } else {
        ArrayList<UserModel> userModelList = new ArrayList<UserModel>();

        try {
          UserCenterParse getrequest = new UserCenterParse();
          userModelList = getrequest.getMemberInfoByMemberIDParse(result);
          userInformation = new UserModel();
          if (userModelList.size() > 0 || userModelList != null) {
            userInformation = userModelList.get(0);
            ImageLoader.getInstance()
                .displayImage(userInformation.getProfileImage(), profileImage, otp);
            if (userInformation.getGender().equals("Male")) {
              userGender.setImageResource(R.drawable.male_icon);
            } else if (userInformation.getGender().equals("Female")) {
              userGender.setImageResource(R.drawable.female_icon);
            }

            userName.setText(userInformation.getAccountName());
            userSchool.setText(userInformation.getSchool());
            if (followed.equalsIgnoreCase("0")) {
              btnFollowOrUnfollow.setText("+关注");
            } else if (followed.equalsIgnoreCase("1")) {
              btnFollowOrUnfollow.setText("取消关注");
            }
            btnPosts.setText("发帖\n" + userInformation.getTotalThread());
            btnFollowing.setText("关注\n" + userInformation.getFollowingNum());
            btnFollowed.setText("粉丝\n" + userInformation.getFollowedNum());
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }

        new GetUserThreadList(UserInformationActivity.this, 1).execute("");
      }
    }
  public boolean destroy() throws WeiboException {

    String url = URLHelper.GROUP_DESTROY;

    Map<String, String> map = new HashMap<String, String>();
    map.put("access_token", access_token);
    map.put("list_id", list_id);

    String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Post, url, map);

    Gson gson = new Gson();

    Result value = null;
    try {
      value = gson.fromJson(jsonData, Result.class);
    } catch (JsonSyntaxException e) {
      AppLogger.e(e.getMessage());
    }

    return (value != null);
  }
 @Override
 public Deck loadDeck(String name) {
   DeckData data;
   try {
     data = gson.fromJson(readSource(getDeckUri(name)), DeckData.class);
     CardLibrary cl = loadCardLibrary();
     Card identityCard = cl.getCard(data.getIdentity());
     Deck deck = new Deck(cl.getItentity(identityCard.getKey()), data.getName());
     for (CardRef ref : data.getCards()) {
       deck.add(cl.getCard(ref.getCard()), ref.getCount());
     }
     return deck;
   } catch (JsonIOException e) {
     e.printStackTrace();
   } catch (JsonSyntaxException e) {
     e.printStackTrace();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #29
0
 public static void init() {
   gson = new Gson();
   try {
     BufferedReader r = new BufferedReader(new FileReader("conf/level.json"));
     //			r.readLine();
     levelData = gson.fromJson(r, Levels.class);
     r.close();
   } catch (JsonSyntaxException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (JsonIOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #30
0
  public SearchStatusListBean getStatusList() throws WeiboException {

    String url = WeiBoURLs.STATUSES_SEARCH;

    Map<String, String> map = new HashMap<String, String>();
    map.put("access_token", access_token);
    map.put("count", count);
    map.put("page", page);
    map.put("q", q);

    String jsonData = null;

    jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);

    Gson gson = new Gson();

    SearchStatusListBean value = null;
    try {
      value = gson.fromJson(jsonData, SearchStatusListBean.class);
      List<MessageBean> list = value.getItemList();

      Iterator<MessageBean> iterator = list.iterator();
      while (iterator.hasNext()) {
        MessageBean msg = iterator.next();
        // message is deleted by sina
        if (msg.getUser() == null) {
          iterator.remove();
        } else {
          msg.getListViewSpannableString();
          TimeUtility.dealMills(msg);
        }
      }
    } catch (JsonSyntaxException e) {

      AppLoggerUtils.e(e.getMessage());
    }

    return value;
  }