下面列出了com.google.gson.JsonSyntaxException#printStackTrace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static TimeLinePosition getPosition(String accountId) {
String sql = "select * from " + CommentByMeTable.TABLE_NAME + " where " + CommentByMeTable.ACCOUNTID + " = "
+ accountId;
Cursor c = getRsd().rawQuery(sql, null);
Gson gson = new Gson();
while (c.moveToNext()) {
String json = c.getString(c.getColumnIndex(CommentByMeTable.TIMELINEDATA));
if (!TextUtils.isEmpty(json)) {
try {
TimeLinePosition value = gson.fromJson(json, TimeLinePosition.class);
c.close();
return value;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
c.close();
return new TimeLinePosition(0, 0);
}
/**
* josn转arrayList
*
* @param jsonArray
* @return
* @author xuzhixiang
* 2018年5月7日 下午5:49:18
*/
public static ArrayList<?> jsonArrayToArrayList(String jsonArray) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.serializeNulls()
.create();
ArrayList<?> list = null;
try {
Type listType = new TypeToken<ArrayList<?>>() {
}.getType();
list = gson.fromJson(jsonArray, listType);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return list;
}
private static TimeLinePosition getPosition(String accountId) {
String sql = "select * from " + MyStatusTable.TABLE_NAME + " where " + MyStatusTable.ACCOUNTID + " = " + accountId;
Cursor c = getRsd().rawQuery(sql, null);
Gson gson = new Gson();
while (c.moveToNext()) {
String json = c.getString(c.getColumnIndex(MyStatusTable.TIMELINEDATA));
if (!TextUtils.isEmpty(json)) {
try {
TimeLinePosition value = gson.fromJson(json, TimeLinePosition.class);
c.close();
return value;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
c.close();
return new TimeLinePosition(0, 0);
}
public List<CategoryInfo> getLibraryCategoryInfos() {
String data = mPreferences.getString(LIBRARY_CATEGORIES, null);
if (data != null) {
Gson gson = new Gson();
Type collectionType = new TypeToken<List<CategoryInfo>>() {
}.getType();
try {
return gson.fromJson(data, collectionType);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
return getDefaultLibraryCategoryInfos();
}
public static TimeLinePosition getPosition(String accountId) {
String sql = "select * from " + MentionCommentsTable.TABLE_NAME + " where " + MentionCommentsTable.ACCOUNTID
+ " = " + accountId;
Cursor c = getRsd().rawQuery(sql, null);
Gson gson = new Gson();
while (c.moveToNext()) {
String json = c.getString(c.getColumnIndex(MentionCommentsTable.TIMELINEDATA));
if (!TextUtils.isEmpty(json)) {
try {
TimeLinePosition value = gson.fromJson(json, TimeLinePosition.class);
c.close();
return value;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
c.close();
return new TimeLinePosition(0, 0);
}
private List<EpisodeModel> readEntriesArray(JsonReader reader) throws IOException {
reader.beginArray();
Gson gson = new GsonBuilder().create();
List<EpisodeModel> all = new ArrayList<>();
while (reader.hasNext()) {
try {
Entry entry = gson.fromJson(reader, Entry.class);
EpisodeModel ep = EpisodeModel.create(entry);
all.add(ep);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
reader.endArray();
return all;
}
@Override
public void loadModel() {
try {
this.entityFitnessMap = GlobalWarming.getInstance().getGson().fromJson(
super.getContents(),
new TypeToken<Map<EntityType, MobDistribution>>() {
}.getType());
} catch (JsonSyntaxException ex) {
ex.printStackTrace();
GlobalWarming.getInstance().getLogger().severe("Error loading model file: " + super.getPath());
GlobalWarming.getInstance().getLogger().severe("Could not load into the expected <EntityType, MobDistribution> mapping.");
GlobalWarming.getInstance().getLogger().severe("Please check the formatting and verify the types are correct.");
return;
}
if (this.entityFitnessMap == null) {
throw new RuntimeException(String.format("No values found in: [%s]", super.getPath()));
}
}
private static TimeLinePosition getPosition(String accountId) {
String sql = "select * from " + MyStatusTable.TABLE_NAME + " where " + MyStatusTable.ACCOUNTID + " = " + accountId;
Cursor c = getRsd().rawQuery(sql, null);
Gson gson = new Gson();
while (c.moveToNext()) {
String json = c.getString(c.getColumnIndex(MyStatusTable.TIMELINEDATA));
if (!TextUtils.isEmpty(json)) {
try {
TimeLinePosition value = gson.fromJson(json, TimeLinePosition.class);
c.close();
return value;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
c.close();
return new TimeLinePosition(0, 0);
}
@Override
public void log( String message ){
final String logName = "OkHttp";
if( !message.startsWith( "{" ) ){
Log.d( logName, message );
return;
}
try{
String prettyPrintJson = new GsonBuilder()
.setPrettyPrinting()
.create()
.toJson( new JsonParser().parse( message ) );
Logger.init().methodCount( 1 ).hideThreadInfo();
Logger.t( logName ).json( prettyPrintJson );
}catch( JsonSyntaxException m ){
Log.e( TAG, "html header parse failed" );
m.printStackTrace();
Log.e( logName, message );
}
}
public static TimeLinePosition getPosition(String accountId) {
String sql = "select * from " + CommentsTable.TABLE_NAME + " where " + CommentsTable.ACCOUNTID + " = " + accountId;
Cursor c = getRsd().rawQuery(sql, null);
Gson gson = new Gson();
while (c.moveToNext()) {
String json = c.getString(c.getColumnIndex(CommentsTable.TIMELINEDATA));
if (!TextUtils.isEmpty(json)) {
try {
TimeLinePosition value = gson.fromJson(json, TimeLinePosition.class);
c.close();
return value;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
c.close();
return new TimeLinePosition(0, 0);
}
/**
* 解析ResultListBundle
*
* @param json 服务器返回的json数据
* @param <T>
* @return
*/
public <T> ResultListBundle<T> listBundle(String json) {
ResultListBundle<T> resultBundle = null;
try {
Type objectType = new TypeToken<ResultListBundle<T>>() {
}.getType();
resultBundle = gson.fromJson(json, objectType);
} catch (JsonSyntaxException e) {
LOG.error("无法解析的返回值信息:" + json);
e.printStackTrace();
}
validate(resultBundle);
return resultBundle;
}
private void praseDataByJson(String json, int type) {
try {
MusicMainData musicMainData = DOkHttp.getInstance().getGson().fromJson(json, MusicMainData.class);
if (musicMainData.getData() != null && musicMainData.getData().getSongs() != null && musicMainData.getData().getSongs().size() > 0) {
AppRunCache.musicList.clear();
for (int i = 0; i < musicMainData.getData().getSongs().size(); i++) {
if (musicMainData.getData().getSongs().get(i).getUrlList() != null && musicMainData.getData().getSongs().get(i).getUrlList().size() > 0) {
lists.add(musicMainData.getData().getSongs().get(i));
AppRunCache.musicList.add(lists.get(i).getUrlList().get(0).getUrl());
}
}
if (isFirst) {
getActivity().startService(service);
}
//重置
if (type == 1) {
Intent intent0 = new Intent(IntentFilterUtils.Music_Reset);
mLocalBroadcastManager.sendBroadcast(intent0);
}
iView.setSongName(lists.get(current_index_playing));
if (type == 0) {
//获取第一首歌的播放数据
showSongMsg(lists.get(current_index_playing));
}
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
ToastUtil.showToast("praseDataByJson Error");
}
}
/**
* @param src :将要被转化的对象
* @return :转化后的JSON串
* @MethodName : toJson
* @Description : 将对象转为JSON串,此方法能够满足大部分需求
*/
public static String toJson(Object src) {
if (null == src) {
return gson.toJson(JsonNull.INSTANCE);
}
try {
return gson.toJson(src);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return null;
}
/**
* @param json
* @param classOfT
* @return
* @MethodName : fromJson
* @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
*/
public static <T> Object fromJson(String json, Class<T> classOfT) {
try {
return gson.fromJson(json, (Type) classOfT);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return null;
}
private void parseContent(String content) {
String f = "var playerParams = {";
int pos = content.indexOf(f);
if (pos >= 0) {
int start = pos + f.length();
int end = content.indexOf("};", start);
if (end > pos) {
String data = content.substring(start - 1, end + 1);
Log.d(TAG, "data:" + data);
Gson gson = new Gson();
try {
PlayerParams params = gson.fromJson(data, PlayerParams.class);
Log.d(TAG, "params: " + params);
if (params != null && params.releaseUrls != null) {
String release = params.releaseUrls.getUrl();
if (release != null && release.length() > 0) {
Uri.Builder builder = Uri.parse(release).buildUpon();
Uri url = builder.build();
loadPlayList(url);
return;
}
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
}
ContentManager.getInstance().broadcastChange(ContentManager.CONTENT_AUTH_ERROR, ContentManager.AUTH_FAILED_TOKEN, id);
}
public static BlockVariant deserializeVariant(String key, JsonElement variant)
{
List<VariantModel> models = new ArrayList<>();
try {
if (variant.isJsonObject()) //If only a single model
variant = new JsonParser().parse("[" + variant.toString() + "]");
models = new Gson().fromJson(variant.getAsJsonArray(), new TypeToken<List<VariantModel>>(){}.getType());
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return new BlockVariant(key, models);
}
public CapeConfig parse(InputStream is) {
if (is == null) {
throw new NullPointerException("Can not parse a null input stream!");
}
CapeConfig instance = new CapeConfig();
InputStreamReader isr = new InputStreamReader(is);
try {
Map<String, Object> entries = new Gson().fromJson(isr, Map.class);
for (Map.Entry<String, Object> entry : entries.entrySet()) {
final String nodeName = entry.getKey();
final Object obj = entry.getValue();
if (obj instanceof Map) {
parseGroup(instance, nodeName, (Map) obj);
} else if (obj instanceof String) {
parseUser(instance, nodeName, (String) obj);
}
}
} catch (JsonSyntaxException e) {
DevCapes.logger.error("CapeConfig could not be parsed because:");
e.printStackTrace();
}
return instance;
}
/**
* 解析ResultListBundle
*
* @param json 服务器返回的json数据
* @param <T>
* @return
*/
public <T> ResultListBundle<T> listBundle(String json) {
ResultListBundle<T> resultBundle = null;
try {
Type objectType = new TypeToken<ResultListBundle<T>>() {
}.getType();
resultBundle = gson.fromJson(json, objectType);
} catch (JsonSyntaxException e) {
LOG.error("无法解析的返回值信息:" + json);
e.printStackTrace();
}
validate(resultBundle);
return resultBundle;
}
/**
* using AJAX api now: http://msdn.microsoft.com/en-us/library/ff512402.aspx
*
* @param accessToken
* @param querys
* @param from
* @param to
* @return list of String, which is the result
*/
public static List<String> getTranslatedStringArrays2(String accessToken, List<String> querys, SupportedLanguages from, SupportedLanguages to) {
// Log.i(querys.toString());
String url = generateUrl(accessToken, querys, from, to);
Header[] headers = new Header[]{
new BasicHeader("Authorization", "Bearer " + accessToken),
new BasicHeader("Content-Type", "text/plain; charset=" + ENCODING),
new BasicHeader("Accept-Charset", ENCODING)
};
String getResult = HttpUtils.doHttpGet(url, headers);
// Log.i(getResult);
JsonArray jsonArray = null;
try {
jsonArray = new JsonParser().parse(getResult).getAsJsonArray();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
if (jsonArray == null)
return null;
// Log.i("jsonArray.size: " + jsonArray.size());
List<String> result = new ArrayList<String>();
for (int i = 0; i < jsonArray.size(); i++) {
String translatedText = jsonArray.get(i).getAsJsonObject().get("TranslatedText").getAsString();
if (translatedText == null) {
result.add("");
} else {
result.add(StringEscapeUtils.unescapeJava(translatedText));
}
}
if (querys.size() > result.size()) {
for (int i = 0; i < querys.size(); i++) {
if (querys.get(i).isEmpty()) {
result.add(i, "");
}
if (querys.size() == result.size())
break;
}
}
Log.i(result.toString());
return result;
}
/**
*
* @param url
* @param clazz
* @param listener
* @param errorListener
* @param keys
* @param values
*/
public void getWithParams(String url, Class clazz, Response.Listener listener, Response.ErrorListener errorListener, String[] keys, String[] values){
Map<String, String> params = new HashMap<String, String>();
for (int i = 0; i < keys.length; i++) {
params.put(keys[i], values[i]);
}
GsonRequest request = new GsonRequest(Request.Method.GET, getAbsoluteUrl(url), clazz, null, params, listener, errorListener);
HttpService.httpQueue.getCache().invalidate(getAbsoluteUrl(url), true);
if(!NetWorkUtils.detect(httpService.getContext()))
{
if (HttpService.httpQueue.getCache().get(getAbsoluteUrl(url)) !=null){
String cacheStr = new String(HttpService.httpQueue.getCache().get(getAbsoluteUrl(url)).data);
if (cacheStr != null){
try {
listener.onResponse(gson.fromJson(cacheStr, clazz));
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return;
}
}
return;
}
httpService.addToRequestQueue(request);
}