gpt4 book ai didi

android - 如何在android中解析复杂的JSON文件

转载 作者:行者123 更新时间:2023-11-29 15:25:34 25 4
gpt4 key购买 nike

我需要解析这个json字符串

 {
"results": {
"result": [
{
"cover": "http://ia.media-imdb.com/images/M/MV5BMjMyOTM4MDMxNV5BMl5BanBnXkFtZTcwNjIyNzExOA@@._V1._SX54_CR0,0,54,74_.jpg",
"title": "The Amazing Spider-Man",
"year": "(2012",
"director": "Marc Webb",
"rating": "7.3",
"details": "http://www.imdb.com/title/tt0948470/"
},
{
"cover": "http://i.media-imdb.com/images/SF1f0a42ee1aa08d477a576fbbf7562eed/realm/feature.gif",
"title": "The Amazing Spider-Man 2",
"year": "(2014",
"director": "N/A",
"rating": "N/A",
"details": "http://www.imdb.com/title/tt1872181/"
},
{
"cover": "http://ia.media-imdb.com/images/M/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,0,54,74_.jpg",
"title": "Spider-Man",
"year": "(2002",
"director": "Sam Raimi",
"rating": "7.3",
"details": "http://www.imdb.com/title/tt0145487/"
},
{
"cover": "http://ia.media-imdb.com/images/M/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ@@._V1._SX54_CR0,0,54,74_.jpg",
"title": "Spider-Man 3",
"year": "(2007",
"director": "Sam Raimi",
"rating": "6.3",
"details": "http://www.imdb.com/title/tt0413300/"
},
{
"cover": "http://ia.media-imdb.com/images/M/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ@@._V1._SX54_CR0,0,54,74_.jpg",
"title": "Spider-Man 2",
"year": "(2004",
"director": "Sam Raimi",
"rating": "7.5",
"details": "http://www.imdb.com/title/tt0316654/"
}
]
}
}

我获得了所有数据...但是我无法显示从“封面”标签中获得的图像网址...从现在开始最简单的方法是什么...? http://ia.media-imdb.com/images/M/MV5BMjMyOTM4MDMxNV5BMl5BanBnXkFtZTcwNjIyNzExOA@@._V1._SX54_CR0,0,54,74_.jpg


我已经从 http json 数据在 ListView 中实现了 Android 延迟加载图像和文本,现在我想让列表项可点击,但我无法弄清楚在这种情况下如何做到这一点

    public class MainActivity extends Activity {

ListView mListView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView txts=(TextView) findViewById(R.id.textView1);
String URL1=getIntent().getExtras().getString("URL");


// URL to the JSON data
String strUrl = URL1;

// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();

// Starting the download process
downloadTask.execute(strUrl);

// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);


}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}

data = sb.toString();

br.close();

}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}

return data;
}



/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);

}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}

@Override
protected void onPostExecute(String result) {

// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

// Start parsing xml data
listViewLoaderTask.execute(result);

}
}

/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}

// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();

// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;

try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}

// Keys used in Hashmap
String[] from = { "country","flag","details"};

// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};

// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries,
return adapter;
}

/** Invoked by the Android on "doInBackground" is executed */
@Override
protected void onPostExecute(SimpleAdapter adapter) {

// Setting adapter for the listview
mListView.setAdapter(adapter);

for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);

// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}

/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<St

@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");

URL url;
try {
url = new URL(imgUrl);

// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();

// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");

// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);

// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);

// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

// Flush the FileOutputStream
fOutStream.flush();

//Close the FileOutputStream
fOutStream.close();

// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());

// Storing the position of the image in the listview
hmBitmap.put("position",position);

// Returning the HashMap object containing the image path and position
return hmBitmap;


}catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");

// Getting the position of the downloaded image
int position = (Integer) result.get("position");

// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);

// Overwriting the existing path in the adapter
hm.put("flag",path);

// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

如何做到?

最佳答案

首先请看一些教程,例如:

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

http://www.vogella.com/articles/AndroidJSON/article.html

JSONObject response = new JSONObject(respString);
ArrayList<Book> bookCollection = new ArrayList<Book>();//
if(response.has("results")){
if(response.has("result")){
JSONArray resultArray = response.getJSONArray("result");
for(int iCount=0; iCount<resultArray.length; iCount++){
JSONObject item = resultArray.getJSONObject(iCount);
Book book = new Book();
if(item.has("title")){
book.title =item.getString("title");
}
bookCollection.add(book);
}
}
}

要填充的 pojo

public Book{

public String cover;
public String title;

}

关于android - 如何在android中解析复杂的JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13576676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com