码迷,mamicode.com
首页 > 移动开发 > 详细

手机端解析json

时间:2015-11-04 19:25:18      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

首先要搭建服务器

package com.json.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.json.service.JSONService;
import com.json.tools.JsonTools;

public class JsonAction extends HttpServlet {
    private JSONService service;

    
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void init() throws ServletException {
        // Put your code here
        service = new JSONService();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String flag = request.getParameter("flag");
        String msg = "";
        if (flag.equals("person")) {
            msg = JsonTools.CreateJaso("person", service.getPerson());
        }else if(flag.equals("persons")){
            msg = JsonTools.CreateJaso("persons", service.getListPerson());
        }else if(flag.equals("liststring")){
            msg = JsonTools.CreateJaso("liststring", service.getListString());
        }else if(flag.equals("listmap")){
            
            msg = JsonTools.CreateJaso("listmap", service.getListMaps());
        }
        out.print(msg);
        out.flush();
        out.close();
    }

    

}

然后我们要通过手机端进行网络连接,根据传入参数的不同得到不同的json字符串

package com.example.jiexijson.tools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpTools {
    public static String getContent(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                InputStream in = conn.getInputStream();
                return getStringFromInput(in);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return path;
    }

    private static String getStringFromInput(InputStream in) {
        byte[] b = new byte[1024];
        int len = 0;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            while ((len = in.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new String(outputStream.toByteArray());

    }
}

然后我们要对这个json字符串进行解析,服务器中发出来的是什么对象,我们就要通过这个字符串把它还原回去

package com.example.jiexijson.jsontools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.jiexijson.bean.Person;

public class FindJson {
    //把json字符串解析成对象。     json字符串的key  json字符串
    public static Person getPerson(String key,String json){
        Person person = new Person();
        try {
            //返回一个json对象
            JSONObject jsonObject = new JSONObject(json);
            //取出键以后的部分
            JSONObject getValue = jsonObject.getJSONObject(key);
            //服务器传过来是对象,解析就要是一个对象。
            person.setId(getValue.getInt("id"));
            person.setName(getValue.getString("name"));
            person.setAddress(getValue.getString("address"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return person;
    }
    public static List<Person> getListPerson(String key,String json){
        List<Person> list = new ArrayList<Person>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            //返回json数组
            JSONArray value = jsonObject.getJSONArray(key);
            for (int i = 0; i < value.length(); i++) {
                Person person = new Person();
                //返回数组里的json对象,然后进行取出
                JSONObject getValue = value.getJSONObject(i);
                person.setId(getValue.getInt("id"));
                person.setName(getValue.getString("name"));
                person.setAddress(getValue.getString("address"));
                list.add(person);
                
            }
            
            
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        return list;
    }
    public static List<String> getListString(String key,String json){
        List<String> list = new ArrayList<String>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray array = jsonObject.getJSONArray(key);
            for (int i = 0; i < array.length(); i++) {
                //取出数组里的字符串
                list.add(array.getString(i));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
    public static List<Map<String, Object>> getListMap(String key,String json){
         List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
         try {
             //返回json字符串返回json对象
            JSONObject jsonObject = new JSONObject(json);
            //通过key来取得json对象的数组部分
            JSONArray array = jsonObject.getJSONArray(key);
            
            for (int i = 0; i < array.length(); i++) {
                //把每一个数组返回一个可以解析的json对象
                JSONObject value = array.getJSONObject(i);
                
                Map<String,Object> map = new HashMap<String, Object>();
                //遍历里面的键
                Iterator<String> iterator = value.keys();
                //判断还有没有下一个
                while(iterator.hasNext()){
                    //取得json的key
                    String json_key = iterator.next();
                    //通过key取得json的值
                    Object json_object = value.get(json_key);
                    if(json_object==null){
                        json_object = "";
                    }
                    //加到map集合里
                    map.put(json_key, json_object);
                    list.add(map);
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
}

最后我们就要在activity里通过点击事件调用了

package com.example.jiexijson;

import java.util.List;
import java.util.Map;

import com.example.jiexijson.bean.Person;
import com.example.jiexijson.jsontools.FindJson;
import com.example.jiexijson.tools.HttpTools;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
    private Button person;
    private Button persons;
    private Button liststring;
    private Button listmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        person = (Button) findViewById(R.id.btn_person);
        persons = (Button) findViewById(R.id.btn_persons);
        liststring = (Button) findViewById(R.id.btn_liststring);
        listmap = (Button) findViewById(R.id.btn_listmap);
        person.setOnClickListener(this);
        persons.setOnClickListener(this);
        liststring.setOnClickListener(this);
        listmap.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_person:
            String path = "http://192.168.21.1:8080/json/servlet/JsonAction?flag=person";
            //获得json的数组形式,但还是要解析成person对象
            String jsonString = HttpTools.getContent(path);
            //返回json解析后的对象
            Person person = FindJson.getPerson("person", jsonString);
            System.out.println(person.toString());
            break;
        case R.id.btn_persons:
            String path1 = "http://192.168.21.1:8080/json/servlet/JsonAction?flag=persons";
            String jsonString2 = HttpTools.getContent(path1);
            List<Person> list = FindJson.getListPerson("persons", jsonString2);
            System.out.println(list.toString());
            break;
        case R.id.btn_liststring:
            String path2 = "http://192.168.21.1:8080/json/servlet/JsonAction?flag=liststring";
            String jsonString3 = HttpTools.getContent(path2);
            List<String> listString = FindJson.getListString("liststring",jsonString3);
            System.out.println(listString.toString());
            break;
        case R.id.btn_listmap:
            String path3 = "http://192.168.21.1:8080/json/servlet/JsonAction?flag=listmap";
            String jsonString4 = HttpTools.getContent(path3);
            List<Map<String, Object>> listmap = FindJson.getListMap("listmap", jsonString4);
            System.out.println(listmap.toString());
            break;
        }
    }

}

 

手机端解析json

标签:

原文地址:http://www.cnblogs.com/84126858jmz/p/4936808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!