获取网络上的json数据
2013-11-06 16:52
232 查看
1.新建一个web项目,使用json显示数据
(1)实体类News
News.java
(2)建立业务Bean
NewsService .java
(3)新建业务实现类(添加数据)
NewsServiceBean.java
(4)新建servlet
NewsListServlet.java
(5)jsp页面
News1.jsp(注意:ontentType="text/plain”)
<%@ page language="java" contentType="text/plain”; charset=utf-8"
pageEncoding="utf-8"%>
${json}
运行web项目,结果为:
注意:
我们新建一个jsp页面
News.jsp
Servlet调转到这个页面,结果为:
对比之后,发现调转到News.jsp页面后多出了红色部分。所以在android中json是无法解析的。所以不要调转News.jsp。
2.创建android项目,访问web
(1)添加网络访问权限
<category android:name="android.intent.category.LAUNCHER" />
(2)界面布局
Activity_main.xml
items.xml
(3)实体类
News.java
(4)工具类StreamTool.java 读取字节
(5)业务类
(7)MainActivity.java
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获取数据结果:
相关文章推荐
- android天气查询(二)之网络json数据的获取
- 用异步获取网络数据Json
- android:通过url向网络端获取json格式数据并解析显示
- Android开发18——获取网络资源之json数据
- Android Studio获取网络JSON数据并处理的方法
- Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
- Android网络编程之获取网络上的Json数据实例
- Android开发18——获取网络资源之json数据
- 从网络获取JSON格式数据
- json数据解析,并实现将网络json数据获取用listview显示
- JSON异步获取网络数据
- JSONObject 解析从网络获取的json数据时,java.lang.String cannot be converted to JSONObject解决办法(编码 UTF-8)
- 从网络获取JSON格式数据
- Android - 获取网络数据,Bitmap,ANR,主线程模型,消息机制,UserAgent,乱码问题,xml生成与解析,JSON解析,MVC,SmartImageView
- Android 网络获取数据之Json解析
- AsyncTask 网络获取图片和Json数据加载到ListView上
- java,android中网络数据获取和json解析
- 如何从网络中获取json数据信息
- Android开发18——获取网络资源之json数据
- Antd中Table控件呈现网络获取的json数据