博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android解析服务器Json数据实例
阅读量:6247 次
发布时间:2019-06-22

本文共 22579 字,大约阅读时间需要 75 分钟。

Json数据信息如下:

{  "movies": [    {      "movie": "Avengers",      "year": 2012,      "rating": 7.8,      "duration": "141 min",      "director": "Joss Whedon",      "tagline": "A new age begins",      "cast": [        {          "name": "Robert Downey Jr."        },        {          "name": "Chris Evans"        },        {          "name": "Mark Ruffalo"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/avengers.jpg",      "story": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's Mightiest Heroes to stop the villainous Ultron from enacting his terrible plans."    },    {      "movie": "Interstellar",      "year": 2014,      "rating": 8.7,      "duration": "169 min",      "director": "Christopher Nolan",      "tagline": "Mankind was born on Earth. It was never meant to die here.",      "cast": [        {          "name": "Matthew McConaughey"        },        {          "name": "Anne Hathaway"        },        {          "name": "Jessica Chastain"        },        {          "name": "Wes Bentley"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/interstellar.jpg",      "story": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival."    },    {      "movie": "Fantastic Four",      "year": 2015,      "rating": 4.0,      "duration": "100 min",      "director": "Josh Trank",      "tagline": "Change is coming.",      "cast": [        {          "name": "Miles Teller"        },        {          "name": "Kate Mara"        },        {          "name": "Michael B. Jordan"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/four.jpg",      "story": "Four young outsiders teleport to an alternate and dangerous universe which alters their physical form in shocking ways. The four must learn to harness their new abilities and work together to save Earth from a former friend turned enemy."    },    {      "movie": "The Dark Knight",      "year": 2008,      "rating": 9.0,      "duration": "152 min",      "director": "Christopher Nolan",      "tagline": "Why So Serious?",      "cast": [        {          "name": "Christian Bale"        },        {          "name": "Heath Ledger"        },        {          "name": "Aaron Eckhart"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/batman.jpg",      "story": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice."    },    {      "movie": "The Lord of the Rings: The Return of the King",      "year": 2003,      "rating": 8.9,      "duration": "201 min",      "director": "Peter Jackson",      "tagline": "This Christmas the journey ends.",      "cast": [        {          "name": "Viggo Mortensen"        },        {          "name": "Ian McKellen"        },        {          "name": "Elijah Wood"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/rings.jpg",      "story": "Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring."    },    {      "movie": "Life Is Beautiful",      "year": 1997,      "rating": 8.6,      "duration": "116 min",      "director": "Roberto Benigni",      "tagline": "An unforgettable fable that proves love, family and imagination conquer all.",      "cast": [        {          "name": "Roberto Benigni"        },        {          "name": "Nicoletta Braschi"        },        {          "name": "Giorgio Cantarini"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/life.jpg",      "story": "When an open-minded Jewish librarian and his son become victims of the Holocaust, he uses a perfect mixture of will, humor and imagination to protect his son from the dangers around their camp."    },    {      "movie": "Gladiator",      "year": 2000,      "rating": 8.5,      "duration": "155 min",      "director": "Ridley Scott",      "tagline": "Father of a murdered son, husband to a murdered wife and I shall have my vengeance in this life or the next",      "cast": [        {          "name": "Russell Crowe"        },        {          "name": "Joaquin Phoenix"        },        {          "name": "Connie Nielsen"        },        {          "name": "Oliver Reed"        },        {          "name": "Tommy Flanagan"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/gladiator.jpg",      "story": "When a Roman general is betrayed and his family murdered by an emperor's corrupt son, he comes to Rome as a gladiator to seek revenge."    },    {      "movie": "The Lion King",      "year": 1994,      "rating": 8.5,      "duration": "89 min",      "director": "Roger Allers",      "tagline": "The King Has Returned.",      "cast": [        {          "name": "James Earl Jones"        },        {          "name": "Jeremy Irons"        },        {          "name": "Matthew Broderick"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/lionking.jpg",      "story": "Lion cub and future king Simba searches for his identity. His eagerness to please others and penchant for testing his boundaries sometimes gets him into trouble."    },    {      "movie": "WALL-E",      "year": 2008,      "rating": 8.4,      "duration": "98 min",      "director": "Andrew Stanton",      "tagline": "He's got a lot of time on his hands.",      "cast": [        {          "name": "Ben Burtt"        },        {          "name": "Elissa Knight"        },        {          "name": "Jeff Garlin"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/walle.jpg",      "story": "In the distant future, a small waste collecting robot inadvertently embarks on a space journey that will ultimately decide the fate of mankind."    },    {      "movie": "Saving Private Ryan",      "year": 1998,      "rating": 8.6,      "duration": "169 min",      "director": "Steven Spielberg",      "tagline": "There was only one man left in the family, and the mission was to save him",      "cast": [        {          "name": "Tom Hanks"        },        {          "name": "Matt Damon"        }      ],      "image": "http://jsonparsing.parseapp.com/jsonData/images/ryan.jpg",      "story": "Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action."    }     ]}

以下为Android源码:

1、activity_detail.xml

2、activity_main.xml

3、row.xml

4、res/drawable/rounded_bg.xml

5、MovieModel.java

package com.hisham.jsonparsingdemo.models;import com.google.gson.annotations.SerializedName;import java.util.List;/** * Created by hisham on 9/6/2015. */public class MovieModel {    private String movie;    private int year;    private float rating;    private String duration;    private String director;    private String tagline;    @SerializedName("cast")    private List
castList; private String image; private String story; public String getMovie() { return movie; } public void setMovie(String movie) { this.movie = movie; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public String getTagline() { return tagline; } public void setTagline(String tagline) { this.tagline = tagline; } public List
getCastList() { return castList; } public void setCastList(List
castList) { this.castList = castList; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getStory() { return story; } public void setStory(String story) { this.story = story; } public static class Cast { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }}

6、DetailActivity.java

package com.hisham.jsonparsingdemo;import android.graphics.Bitmap;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.MenuItem;import android.view.View;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.RatingBar;import android.widget.TextView;import com.google.gson.Gson;import com.hisham.jsonparsingdemo.models.MovieModel;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.assist.FailReason;import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;public class DetailActivity extends ActionBarActivity {    private ImageView ivMovieIcon;    private TextView tvMovie;    private TextView tvTagline;    private TextView tvYear;    private TextView tvDuration;    private TextView tvDirector;    private RatingBar rbMovieRating;    private TextView tvCast;    private TextView tvStory;    private ProgressBar progressBar;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_detail);        // Showing and Enabling clicks on the Home/Up button        if(getSupportActionBar() != null) {            getSupportActionBar().setDisplayHomeAsUpEnabled(true);            getSupportActionBar().setDisplayShowHomeEnabled(true);        }        // setting up text views and stuff        setUpUIViews();        // recovering data from MainActivity, sent via intent        Bundle bundle = getIntent().getExtras();        if(bundle != null){            String json = bundle.getString("movieModel");            MovieModel movieModel = new Gson().fromJson(json, MovieModel.class);            // Then later, when you want to display image            ImageLoader.getInstance().displayImage(movieModel.getImage(), ivMovieIcon, new ImageLoadingListener() {                @Override                public void onLoadingStarted(String imageUri, View view) {                    progressBar.setVisibility(View.VISIBLE);                }                @Override                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {                    progressBar.setVisibility(View.GONE);                }                @Override                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {                    progressBar.setVisibility(View.GONE);                }                @Override                public void onLoadingCancelled(String imageUri, View view) {                    progressBar.setVisibility(View.GONE);                }            });            tvMovie.setText(movieModel.getMovie());            tvTagline.setText(movieModel.getTagline());            tvYear.setText("Year: " + movieModel.getYear());            tvDuration.setText("Duration:" + movieModel.getDuration());            tvDirector.setText("Director:" + movieModel.getDirector());            // rating bar            rbMovieRating.setRating(movieModel.getRating() / 2);            StringBuffer stringBuffer = new StringBuffer();            for(MovieModel.Cast cast : movieModel.getCastList()){                stringBuffer.append(cast.getName() + ", ");            }            tvCast.setText("Cast:" + stringBuffer);            tvStory.setText(movieModel.getStory());        }    }    private void setUpUIViews() {        ivMovieIcon = (ImageView)findViewById(R.id.ivIcon);        tvMovie = (TextView)findViewById(R.id.tvMovie);        tvTagline = (TextView)findViewById(R.id.tvTagline);        tvYear = (TextView)findViewById(R.id.tvYear);        tvDuration = (TextView)findViewById(R.id.tvDuration);        tvDirector = (TextView)findViewById(R.id.tvDirector);        rbMovieRating = (RatingBar)findViewById(R.id.rbMovie);        tvCast = (TextView)findViewById(R.id.tvCast);        tvStory = (TextView)findViewById(R.id.tvStory);        progressBar = (ProgressBar)findViewById(R.id.progressBar);    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == android.R.id.home) {            finish();        }        return super.onOptionsItemSelected(item);    }}

7、MainActivity.java

package com.hisham.jsonparsingdemo;import android.app.ProgressDialog;import android.content.Context;import android.content.Intent;import android.graphics.Bitmap;import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.ProgressBar;import android.widget.RatingBar;import android.widget.TextView;import android.widget.Toast;import com.google.gson.Gson;import com.hisham.jsonparsingdemo.models.MovieModel;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import com.nostra13.universalimageloader.core.assist.FailReason;import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.List;public class MainActivity extends ActionBarActivity {    private final String URL_TO_HIT = "http://jsonparsing.parseapp.com/jsonData/moviesData.txt";    private TextView tvData;    private ListView lvMovies;    private ProgressDialog dialog;    // Git error fix - http://stackoverflow.com/questions/16614410/android-studio-checkout-github-error-createprocess-2-windows    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        dialog = new ProgressDialog(this);        dialog.setIndeterminate(true);        dialog.setCancelable(false);        dialog.setMessage("Loading. Please wait...");        // Create default options which will be used for every        //  displayImage(...) call if no options will be passed to this method        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()                .cacheInMemory(true)                .cacheOnDisk(true)        .build();        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())        .defaultDisplayImageOptions(defaultOptions)        .build();        ImageLoader.getInstance().init(config); // Do it on Application start        lvMovies = (ListView)findViewById(R.id.lvMovies);        // To start fetching the data when app start, uncomment below line to start the async task.                new JSONTask().execute(URL_TO_HIT);    }    public class JSONTask extends AsyncTask
>{ @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); } @Override protected List
doInBackground(String... params) { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(params[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line =""; while ((line = reader.readLine()) != null){ buffer.append(line); } String finalJson = buffer.toString(); JSONObject parentObject = new JSONObject(finalJson); JSONArray parentArray = parentObject.getJSONArray("movies"); List
movieModelList = new ArrayList<>(); Gson gson = new Gson(); for(int i=0; i
castList = new ArrayList<>();// for(int j=0; j
result) { super.onPostExecute(result); dialog.dismiss(); if(result != null) { MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result); lvMovies.setAdapter(adapter); lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView
parent, View view, int position, long id) { MovieModel movieModel = result.get(position); Intent intent = new Intent(MainActivity.this, DetailActivity.class); intent.putExtra("movieModel", new Gson().toJson(movieModel)); startActivity(intent); } }); } else { Toast.makeText(getApplicationContext(), "Not able to fetch data from server, please check url.", Toast.LENGTH_SHORT).show(); } } } public class MovieAdapter extends ArrayAdapter{ private List
movieModelList; private int resource; private LayoutInflater inflater; public MovieAdapter(Context context, int resource, List
objects) { super(context, resource, objects); movieModelList = objects; this.resource = resource; inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null){ holder = new ViewHolder(); convertView = inflater.inflate(resource, null); holder.ivMovieIcon = (ImageView)convertView.findViewById(R.id.ivIcon); holder.tvMovie = (TextView)convertView.findViewById(R.id.tvMovie); holder.tvTagline = (TextView)convertView.findViewById(R.id.tvTagline); holder.tvYear = (TextView)convertView.findViewById(R.id.tvYear); holder.tvDuration = (TextView)convertView.findViewById(R.id.tvDuration); holder.tvDirector = (TextView)convertView.findViewById(R.id.tvDirector); holder.rbMovieRating = (RatingBar)convertView.findViewById(R.id.rbMovie); holder.tvCast = (TextView)convertView.findViewById(R.id.tvCast); holder.tvStory = (TextView)convertView.findViewById(R.id.tvStory); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar); // Then later, when you want to display image ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { progressBar.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { progressBar.setVisibility(View.GONE); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { progressBar.setVisibility(View.GONE); } @Override public void onLoadingCancelled(String imageUri, View view) { progressBar.setVisibility(View.GONE); } }); holder.tvMovie.setText(movieModelList.get(position).getMovie()); holder.tvTagline.setText(movieModelList.get(position).getTagline()); holder.tvYear.setText("Year: " + movieModelList.get(position).getYear()); holder.tvDuration.setText("Duration:" + movieModelList.get(position).getDuration()); holder.tvDirector.setText("Director:" + movieModelList.get(position).getDirector()); // rating bar holder.rbMovieRating.setRating(movieModelList.get(position).getRating()/2); StringBuffer stringBuffer = new StringBuffer(); for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){ stringBuffer.append(cast.getName() + ", "); } holder.tvCast.setText("Cast:" + stringBuffer); holder.tvStory.setText(movieModelList.get(position).getStory()); return convertView; } class ViewHolder{ private ImageView ivMovieIcon; private TextView tvMovie; private TextView tvTagline; private TextView tvYear; private TextView tvDuration; private TextView tvDirector; private RatingBar rbMovieRating; private TextView tvCast; private TextView tvStory; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { new JSONTask().execute(URL_TO_HIT); return true; } return super.onOptionsItemSelected(item); }}

 

转载地址:http://uflia.baihongyu.com/

你可能感兴趣的文章
太阳黑子
查看>>
[转载]date命令时间转换
查看>>
适配iOS11新特性代码在Xcode8 上编译通过的方法
查看>>
别再问什么是Java内存模型了,看这里!
查看>>
2014.5.7—20岁这几年
查看>>
javac - Java programming language compiler
查看>>
异常处理
查看>>
Python多线程程序中的MYSQL连接管理研究
查看>>
Prometheus学习系列(七)之名词解析
查看>>
一文彻底搞懂Dart的event队列
查看>>
iOS面试题06-其他
查看>>
JSON和JSONP
查看>>
2019年互联网女皇趋势报告:小程序创新创业商业模式引领全球
查看>>
C# 递归模型定义。赋值
查看>>
复合文字
查看>>
建立TCP连接的三次握手
查看>>
2017年软件工程第四次作业-1代码规范
查看>>
apache与jetty整合,用mod_proxy
查看>>
[转]使用 C++11 编写 Linux 多线程程序
查看>>
[译]Kinect for Windows SDK开发入门(六):骨骼追踪基础 上
查看>>