Android development-obtain json data of network resources

Source: Internet
Author: User

I. project background there is a very wide application in Android development: the Android project obtains the resources of another web project or the data returned. This document obtains the JSON data returned by the web project. Android applications have better performance in JSON parsing than XML, but many projects still use XML. Ii. instance code Web project [java]/*** News Service class *** @ author Xu Yue **/public class VideoNewsServiceImpl implements VideoNewsService {public List <VideoNews> readNews () {List <VideoNews> lst = new ArrayList <VideoNews> (); lst. add (new VideoNews (1, "Xi Yang", 20); lst. add (new VideoNews (2, "Transformers", 10); lst. add (new VideoNews (3, "Kung Fu pandatv", 20); return lst ;}/ *** news Servlet *** @ author Xu Yue **/public class ListServlet exten Ds HttpServlet {private static final long serialVersionUID = 1L; private VideoNewsService vs = new VideoNewsServiceImpl (); protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {doPost (request, request, response);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {List <Video News> news =. readNews (); JSONArray jsonarr = JSONArray. fromObject (news); response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/plain; charset = UTF-8"); response. setHeader ("Pragma", "No-cache"); response. setHeader ("Cache-Control", "no-cache"); response. setDateHeader ("Expires", 0); response. getWriter (). print (jsonarr) ;}}/*** News Service ** @ author Xu Yue **/public class VideoNewsServiceI Mpl implements VideoNewsService {public List <VideoNews> readNews () {List <VideoNews> lst = new ArrayList <VideoNews> (); lst. add (new VideoNews (1, "Xi Yang", 20); lst. add (new VideoNews (2, "Transformers", 10); lst. add (new VideoNews (3, "Kung Fu pandatv", 20); return lst ;}} /*** news Servlet *** @ author Xu Yue **/public class ListServlet extends HttpServlet {private static final long serialVersionUID = 1L; private VideoNewsService vs = New VideoNewsServiceImpl (); protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {doPost (request, response);} protected void doPost (HttpServletRequest request, response) throws ServletException, IOException {List <VideoNews> news =. readNews (); JSONArray jsonarr = JSONArray. fromObject (news); response. setCharacterEncodi Ng ("UTF-8"); response. setContentType ("text/plain; charset = UTF-8"); response. setHeader ("Pragma", "No-cache"); response. setHeader ("Cache-Control", "no-cache"); response. setDateHeader ("Expires", 0); response. getWriter (). print (jsonarr) ;}} Android project [java] view plaincopyprint? Public class VideoNewsServiceImpl implements VideoNewsService {/*** get the latest video information, from the JSON file, high Resolution efficiency ** @ return * @ throws Exception */public List <VideoNews> getNewsFromJson () throws Exception {List <VideoNews> lst = new ArrayList <VideoNews> (); string path = "http://xxx.xxx.xxx.xxx: 8080/web/ListServlet"; URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setR EadTimeout (5000); conn. setRequestMethod ("GET"); if (200 = conn. getResponseCode () {InputStream instream = conn. getInputStream (); lst = parseJSON (instream);} return lst;}/*** parse JSON */private List <VideoNews> parseJSON (InputStream instream) throws Exception {List <VideoNews> lst = new ArrayList <VideoNews> (); byte [] data = IOUtils. read (instream); String jsonStr = new String (data); JSONArray ar Ray = new JSONArray (jsonStr); for (int I = 0; I <array. length (); I ++) {JSONObject jsonObj = (JSONObject) array. getJSONObject (I); VideoNews v = new VideoNews (jsonObj. getInt ("id"), jsonObj. getString ("title"), jsonObj. getInt ("timeLength"); lst. add (v) ;}return lst ;}} /*** IO tool class ** @ author Xu Yue **/public class IOUtils {/*** read the input stream as byte [] array */public static byte [] read (InputStream instream) t Hrows IOException {ByteArrayOutputStream bos = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = instream. read (buffer ))! =-1) {bos. write (buffer, 0, len);} return bos. toByteArray () ;}} public class videonewsserviceimplements VideoNewsService {/*** get the latest video information, from the JSON file, high Resolution efficiency ** @ return * @ throws Exception */public List <VideoNews> getNewsFromJson () throws Exception {List <VideoNews> lst = new ArrayList <VideoNews> (); string path = "http://xxx.xxx.xxx.xxx: 8080/web/ListServlet"; URL url = new URL (path); HttpURLConnection co Nn = (HttpURLConnection) url. openConnection (); conn. setreadtimeouts (5000); conn. setRequestMethod ("GET"); if (200 = conn. getResponseCode () {InputStream instream = conn. getInputStream (); lst = parseJSON (instream);} return lst;}/*** parse JSON */private List <VideoNews> parseJSON (InputStream instream) throws Exception {List <VideoNews> lst = new ArrayList <VideoNews> (); byte [] data = IOUtils. read (instream); String JsonStr = new String (data); JSONArray array = new JSONArray (jsonStr); for (int I = 0; I <array. length (); I ++) {JSONObject jsonObj = (JSONObject) array. getJSONObject (I); VideoNews v = new VideoNews (jsonObj. getInt ("id"), jsonObj. getString ("title"), jsonObj. getInt ("timeLength"); lst. add (v) ;}return lst ;}} /*** IO tool class ** @ author Xu Yue **/public class IOUtils {/*** read the input stream as byte [] array */public static byte [] read (InputStream instream) throws IOException {ByteArrayOutputStream bos = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = instream. read (buffer ))! =-1) {bos. write (buffer, 0, len);} return bos. toByteArray () ;}}it must be noted that in the web project, I use net. sf. classes in json are parsed, while the default JSON package in Android projects is org. json. The API is different. Just familiarize yourself with it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.