Json data analysis of http communication

How to make data in Json format

  Using gson-2.2.4.jar provided by Google,

    

public class TestJson {

	public static void main(String[] args) {

		Result result = new Result();
		result.setResult(1);
		List<People> peoples = new ArrayList<>();
		People people1 = new People();
		people1.setName("jack");
		people1.setAge(13);
		people1.setUrl("http://hiphotos.baidu.com/9_6kis/pic/item/3b8fe9df2b11c37695ee37c4.jpg");
		List<SchoolInfo> schoolInfo1 = new ArrayList<>();
		SchoolInfo school1 = new SchoolInfo();
		school1.setSchool_name("Tsinghua");
		schoolInfo1.add(school1 );
		SchoolInfo school2 = new SchoolInfo();
		school2.setSchool_name("北大");
		schoolInfo1.add(school2 );
		people1.setSchoolInfo(schoolInfo1 );
		peoples.add(people1);
		
		People people2 = new People();
		people2.setName("rose");
		people2.setAge(13);
		people2.setUrl("http://hiphotos.baidu.com/a03713106460/pic/item/772181666066aa0faa184c1d.jpg");
		List<SchoolInfo> schoolInfo2 = new ArrayList<>();
		SchoolInfo school3 = new SchoolInfo();
		school3.setSchool_name("People's University");
		schoolInfo2.add(school3 );
		SchoolInfo school4 = new SchoolInfo();
		school4.setSchool_name("Jiaotong University");
		schoolInfo2.add(school4 );
		people2.setSchoolInfo(schoolInfo2 );
		peoples.add(people2);
		
		result.setPersonData (peoples);
		
		Gson gson = new Gson ();
		System.out.println(gson.toJson(result));
	}

}

    The completed Json data is put into the http://www.bejson.com website for formatting and validation

   result:

{
    "result": 1,
    "personData": [
        {
            "name": "jack",
            "age": 13,
            "url": "http://hiphotos.baidu.com/9_6kis/pic/item/3b8fe9df2b11c37695ee37c4.jpg",
            "schoolInfo": [
                {
                    "school_name": "清华"
                },
                {
                    "school_name": "北大"
                }
            ]
        },
        {
            "name": "rose",
            "age": 13,
            "url": "http://hiphotos.baidu.com/a03713106460/pic/item/772181666066aa0faa184c1d.jpg",
            "schoolInfo": [
                {
                    "school_name": "人大"
                },
                {
                    "school_name": "交大"
                }
            ]
        }
    ]
}

 

 

1. Open the thread to access the network

       Access the network and read the data in Json format for Json parsing

     

public class HttpJson extends Thread {

    private String url;
    private ListView listView;
    private JsonAdapter adapter ;
    private Handler handler;
    private Context context;
    private static final String TAG = "HttpJson";

    public HttpJson(String url, Context context, ListView listView, JsonAdapter adapter, Handler handler){
        this.url = url;
        this.listView = listView;
        this.adapter = adapter;
        this.handler = handler;
        this.context = context;
    }

    @Override
    public void run() {
        try {
            URL httpurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            //Get the Josn data from the input stream
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String str ;
            while((str = reader.readLine()) != null){
                sb.append(str);
            }
            Log.i(TAG, "run: " + sb.toString());
            final List<People> peoples = parserJson(sb.toString());
            for ( People people : peoples){
                Log.i(TAG, "run: " + people.toString());
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.setPeoples(peoples);
                    listView.setAdapter(adapter);
                }
            });
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }

    /**
     * Parse Json data
     * @param json
     */
    private List<People> parserJson(String json) {
        /*
         *{"result":1,"personData":[{"name":"jack","age":13,"url":"http://hiphotos.baidu.com/9_6kis/pic/item/3b8fe9df2b11c37695ee37c4.jpg","schoolInfo":[{"school_name":"清华"},{"school_name":"北大"}]},{"name":"rose","age":13,"url":"http://hiphotos.baidu.com/a03713106460/pic/item/772181666066aa0faa184c1d.jpg","schoolInfo":[{"school_name":"人大"},{"school_name":"交大"}]}]}
         * Can be parsed in the Josn parser of the www.bejson.com website
         */
        try {
            JSONObject jsonObject = new JSONObject(json);
            List<People> peoples=  new ArrayList<>();
            int result = jsonObject.getInt("result");
            if(result == 1) {
                JSONArray personData = jsonObject.getJSONArray ("personData");
                for(int i = 0 ;i < personData.length();i++){
                    People peopleObject = new People();
                    peoples.add(peopleObject);
                    JSONObject object = personData.getJSONObject(i);
                    String name = object.getString("name");
                    int age = object.getInt("age");
                    String imageUrl = object.getString("url");
                    peopleObject.setName(name);
                    peopleObject.setAge(age);
                    peopleObject.setUrl(imageUrl);
                    JSONArray schoolInfos = object.getJSONArray("schoolInfo");
                    List<SchoolInfo> schInfos = new ArrayList<>();
                    for(int j = 0;j < schoolInfos.length();j++){
                        JSONObject schoolObject = schoolInfos.getJSONObject(j);
                        SchoolInfo school = new SchoolInfo();
                        String school_name = schoolObject.getString("school_name");
                        Log.i(TAG, "parserJson: " + school_name);
                        school.setSchool_name(school_name);
                        schInfos.add(school);
                    }
                    peopleObject.setSchoolInfo(schInfos);
                }
                return  peoples;
            }else{
                Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace ();
        }
        return null;
    }
}

 

 

2. Next is the implementation of JsonAdapter

   Among them is the use of ListView. In getView, open the thread HttpImage to access the network to load pictures,

     

public class JsonAdapter extends BaseAdapter{

    private static final String TAG = "JsonAdapter";
    private Context context;
    private List<People> peoples;
    private LayoutInflater inflater;
    private Handler handler;

    public JsonAdapter(Context context,Handler handler){
        this.context = context;
        this.handler = handler;
        inflater = LayoutInflater.from(context);
    }

    public List<People> getPeoples() {
        return peoples;
    }

    public void setPeoples(List<People> peoples) {
        this.peoples = peoples;
    }

    @Override
    public int getCount() {
        return peoples.size();
    }

    @Override
    public Object getItem(int position) {
        return peoples.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            convertView = inflater.inflate(R.layout.item_listview,null);
            holder = new ViewHolder(convertView);
            convertView.setTag (holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        People people = peoples.get(position);
        if(people != null)
            Log.i(TAG, "getView: " + people.toString());
        holder.name.setText(people.getName());
        holder.age.setText("" + people.getAge());
        holder.school1.setText(people.getSchoolInfo().get(0).getSchool_name());
        holder.school2.setText(people.getSchoolInfo().get(1).getSchool_name());
        new HttpImage(people.getUrl(),handler,holder.imageView).start();
        return convertView;
    }

}
class  ViewHolder {
    ImageView imageView;
    TextView name;
    TextView age;
    TextView school1;
    TextView school2;
    public ViewHolder(View view){
        imageView = (ImageView) view.findViewById(R.id.imageView);
        name = (TextView) view.findViewById(R.id.tv_name);
        age = (TextView) view.findViewById(R.id.tv_age);
        school1 = (TextView) view.findViewById(R.id.school1);
        school2 = (TextView) view.findViewById(R.id.school2);
    }
}

 

 

 3. Load the image thread httpImage

 

public class HttpImage extends Thread{

    private String url;
    private Handler handler;
    private ImageView imageView;
    public HttpImage(String url, Handler handler, ImageView imageView) {
        this.url = url;
        this.handler = handler;
        this.imageView = imageView;
    }

    @Override
    public void run() {
        try {
            URL httpurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream in = conn.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(in);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });
            in.close();
        } catch (ProtocolException e) {
            e.printStackTrace ();
        } catch (MalformedURLException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}

   The specific operation results are as follows

 



 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326858247&siteId=291194637