解析json格式文件
程序员文章站
2022-03-31 17:00:57
...
package example.com.networktest.utility;
import android.nfc.Tag;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import example.com.networktest.bean.App;
public class ParseJSON {
private static final String TAG = "我是ParseJSON";
/* 使用JSONObject 对象来解析JSON格式数据 */
public static void ParseJsonWithJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0 ; i<jsonArray.length() ; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
Log.d(TAG+" JSONObject", "id is :" + id);
Log.d(TAG+" JSONObject", "name is :" + name);
Log.d(TAG+" JSONObject", "version is :" + version);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/* 使用GSON来解析JSON格式数据 */
public static void ParseJsonWithGSON(String jsonData) throws JsonSyntaxException {
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {
}.getType());
for (App app : appList) {
Log.d(TAG, "id is :" + app.getId());
Log.d(TAG, "name is :" + app.getName());
Log.d(TAG, "version is :" + app.getVersion());
}
} }
转载于:https://www.jianshu.com/p/7e19df94403e