您的位置:首页 > 理论基础 > 计算机网络

获取网络上的json数据

2013-11-06 16:52 232 查看
1.新建一个web项目,使用json显示数据







(1)实体类News

News.java

package cn.com.entity;

 

public class News {
    private Integer id;
    private String title;
    private Integer timelength;

    public News(){};

    public News(Integer id,String title,Integer timelength){
       this.id= id;
       this.title=title;
       this.timelength=timelength;
    }

    
    public Integer getId() {
       return id;

    }

   public void setId(Integer id) {
       this.id = id;
   }

   public String getTitle() {
       return title;

   }

   public void setTitle(String title) {
      this.title = title;
   }

   public Integer getTimelength() {
      return timelength;
   }

   public void setTimelength(Integer timelength) {
      this.timelength = timelength;
   }

 }






(2)建立业务Bean

NewsService .java



package cn.com.Bean;
import java.util.List;
import cn.com.entity.News;

public interface NewsService {

    public List<News> getLastNew();
}






(3)新建业务实现类(添加数据)

NewsServiceBean.java



package cn.com.impl;
import java.util.ArrayList;
import java.util.List;
import cn.com.Bean.NewsService;
import cn.com.entity.News;

public class NewsServiceBean implements NewsService {

@Override
   public List<News> getLastNew() {
       List<News> newes = new ArrayList<News>();
       newes.add(new News(12,"猫和老鼠",120));
       newes.add(new News(14,"功夫小子",220));
       newes.add(new News(11,"太极",120));
       newes.add(new News(22,"nba总决赛",180));
       newes.add(new News(15,"非诚勿扰",120));

      return newes;
   }

}






(4)新建servlet

NewsListServlet.java



package cn.com.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.Bean.NewsService;
import cn.com.entity.News;
import cn.com.impl.NewsServiceBean;

/**
 * Servlet implementation class NewsListServlet
 */
public class NewsListServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
     private NewsService service = new  NewsServiceBean();

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
     }

     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<News> newes = service.getLastNew();//获取最新视频
        //拼凑格式:   [{id:20,title:"xxx",timelength:90},{id:20,title:"yyy",timelength:90}]
        StringBuilder json = new StringBuilder();
        json.append("[");
        for(News news:newes){
           json.append("{");
           json.append("id:").append(news.getId()).append(",");
           json.append("title:\"").append(news.getTitle()).append("\","); //title:"xxx"记得转义符
           json.append("timelength:").append(news.getTimelength());
            json.append("},");
         }
       json.deleteCharAt(json.length()-1); //去掉最好一个“,”号
       json.append("]");
       request.setAttribute("json", json.toString());
       request.getRequestDispatcher("News1.jsp").forward(request, response);
}

 

}






(5)jsp页面



News1.jsp(注意:ontentType="text/plain”)

<%@ page language="java" contentType="text/plain”; charset=utf-8"

pageEncoding="utf-8"%>

${json}





运行web项目,结果为:







注意:

我们新建一个jsp页面

News.jsp

<?xml version="1.0" encoding="utf-8" ?>

<%@ page language="java" contentType="text/plain; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert title here</title>

</head>

<body>
   ${json}
</body>
</html>






Servlet调转到这个页面,结果为:







对比之后,发现调转到News.jsp页面后多出了红色部分。所以在android中json是无法解析的。所以不要调转News.jsp。









2.创建android项目,访问web





(1)添加网络访问权限

<category android:name="android.intent.category.LAUNCHER" />





(2)界面布局

Activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android1:id="@+id/listView1"
        android1:layout_width="match_parent"
        android1:layout_height="wrap_content" >
    </ListView>
</LinearLayout>






items.xml



<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
         />

    <TextView
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>








(3)实体类

News.java



package cn.com.entity;

public class News {
    private Integer id;
    private String title;
    private Integer timelength; 

    public News(){};

    public News(Integer id,String title,Integer timelength){
       this.id= id;
       this.title=title;
       this.timelength=timelength;
    }

   public Integer getId() {
       return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }
   
  public String getTitle() {
      return title;
  }

  public void setTitle(String title) {
     this.title = title;
  }

  public Integer getTimelength() {
    return timelength;
  }

  public void setTimelength(Integer timelength) {
    this.timelength = timelength;
  }   

}






(4)工具类StreamTool.java 读取字节



package cn.com.service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamTool {

 public static String read(InputStream inputStream) throws IOException{
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    if((len=inputStream.read(buffer))!=-1){
       os.write(buffer, 0, len);
     }
    byte[] data=os.toByteArray();
    String json = new String(data);
    os.close();
    inputStream.close();
    return json;
 } 

}


(5)业务类



package cn.com.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject; 
import cn.com.entity.News;

public class NewsService {

/**
 * 得到 List<News>
 * @return
 * @throws Exception
 */

  public static List<News> getJSONLastNews() throws Exception{
    List<News> newes = null;
    String path="http://10.162.0.171:8080/ServerForJSON/NewsListServlet";
    URLurl = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
    if(conn.getResponseCode()==200){
       InputStream inputStream=conn.getInputStream();
       newes =  parseJSON(inputStream);//调用json方法获取json数据
    }
    return newes;
 }

/**
 * 获取json数据
 * @param jsonStream
 * @return
 * @throws Exception
 */

 public static List<News> parseJSON(InputStream jsonStream) throws Exception{
    List<News> list = new ArrayList<News>();
    String json = StreamTool.read(jsonStream); 
    JSONArray jsonArray = new JSONArray(json);
    for(int i=0;i<jsonArray.length();i++){
       JSONObject jsonObject = null;
       jsonObject = jsonArray.getJSONObject(i);
       int id = jsonObject.getInt("id");
       String title = jsonObject.getString("title");
       int time = jsonObject.getInt("timelength");
       list.add(new News(id,title,time));
    }
   return list;
 }

}










(7)MainActivity.java



package com.example.getnewinjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.com.entity.News;
import cn.com.service.NewsService;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

    private ListView listView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         listView = (ListView) findViewById(R.id.listView1);
         try {             <pre name="code" class="java">            List<News> list = NewsService.getJSONLastNews();
            List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
            for(News news:list){
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("id", news.getId());
                map.put("title", "电影:"+news.getTitle());
                map.put("time", "时长:"+news.getTimelength());
                data.add(map);
        }
            Log.i("tag", data.toString()); 
            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.items, new String[]{"title","time"}, 
               new int[]{R.id.title,R.id.time});
             listView.setAdapter(adapter);
        } catch (Exception e) { e.printStackTrace(); } }}<pre>








Json获取数据结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: