package com.example.moviesearch;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class ParseJSON {
private ArrayList<Movie> movies;
private String genres;
private String rated;
private String language;
private int rating;
private String country;
private String release_date;
private String title;
private String directors;
private String actors;
private String plot_simple;
private String poster;
private String runtime;
private String imdb_url;
public ArrayList<Movie> parseJson(String json) {
movies = new ArrayList<Movie>();
try {
JSONArray jArray = new JSONArray(json);
for (int i = 0; i < jArray.length(); i++) {
JSONObject j = jArray.getJSONObject(i);
try {
genres = j.getString("genres").replace("[", "")
.replace("]", "").replaceAll("\"", "");
} catch (Exception e) {
genres = "notfound";
}
try {
rated = j.getString("rated");
} catch (Exception e) {
rated = "not found";
}
try {
language = j.getString("language").replace("[", "")
.replace("]", "").replaceAll("\"", "");
} catch (Exception e) {
language = "notfound";
}
try {
rating = j.getInt("rating");
} catch (Exception e) {
rating = 404;
}
try {
country = j.getString("country").replace("[", "")
.replace("]", "").replaceAll("\"", "");
} catch (Exception e) {
country = "not found";
}
try {
release_date = j.getString("release_date");
} catch (Exception e) {
release_date = "notfound";
}
try {
title = j.getString("title").replace("\n", "");
} catch (Exception e) {
title = "notfound";
}
try {
directors = j.getString("directors").replace("[", "")
.replace("]", "").replaceAll("\"", "");
} catch (Exception e) {
directors = "notfound";
}
try {
actors = j.getString("actors").replace("[", "")
.replace("]", "").replaceAll("\"", "");
} catch (Exception e) {
actors = "notfound";
}
try {
plot_simple = j.getString("plot_simple");
} catch (Exception e) {
poster = "notfound";
}
try {
JSONObject c = j.getJSONObject("poster");
poster = c.getString("cover");
} catch (Exception e) {
poster = "notfound";
}
try {
runtime = j.getString("runtime").replace("[", "")
.replace("]", "").replaceAll("\"", "");
} catch (Exception e) {
runtime = "notfound";
}
try {
imdb_url = j.getString("imdb_url");
} catch (Exception e) {
imdb_url = "notfound";
}
Movie movie = new Movie(genres, rated, language, rating,
country, release_date, title, directors, actors,
plot_simple, poster, runtime, imdb_url);
movies.add(movie);
}
} catch (JSONException e) {
Log.e("jsonerror", "", e);
}
return movies;
}
}
我正在制作一个Android应用程序,需要解析json数据。我将这个json数据转换为自定义类。有时我解析的json不存在所以我必须为它设置一个默认值,我觉得这太粗暴了。
答案 0 :(得分:3)
还有一种方法
j.optString("imdb_url", "notfound");
你可以在没有找到值的情况下传递一些默认值 - 所以你不必在每个getString之后捕获异常