• 安卓解析 json 4种格式 全解析


    总共4种json  ,    还提供了 httclient  和 httpurlconnection 2种方式获取json的方法(请把baseurl 改为可以地址比如http://www.sohu.com 不过返回来的不是json

    1  简单的一个  { ,,,,}

    2  里面有数组 { , [{,,},{,,}],}  

    3 直接一个数组

    4 数组里有数组

    5 其他情况? 没有吧,除非json格式不规范

    主代码:

    package com.example.json;

    import java.net.URL;

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

    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends Activity {

      
     private Button btn2;
     private Button btn3;
     private Button btn4;
     private Button btn5;
     private Button btn6;
     private Button btn7;
     
     private TextView txt1;
     private      String baseUrl="http://ip:8088/ship/servlet/getposinfo";
     private  String str=""; 
        private Handler handler=new Handler()
        {
     
      @Override
      public void handleMessage(Message msg) {
          
     //  返回的字符串 直接是个数组
      // [{"devid":"1234567800","latitude":"29.4963","longitude":"116.189","postime":"2014-06-10 12:13:00"},
         // {"devid":"1234567832","latitude":"29.4943","longitude":"1161.129","postime":"2014-06-11 12:13:00"}]
       if (msg.what==1)
       {
        Log.v("zms","使用httpclient,返回的json");
        try {
         JSONArray jsonArray = new JSONArray(String.valueOf(msg.obj));
             txt1.setText(" ");
             str="httpclient:";
         for (int i=0;i<jsonArray.length();i++)
         {
            JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i); 
             str=str+"第"+i+"个,devid:"+jsonObject2.getString("devid")+"维度:"+jsonObject2.getString("latitude")+" ";
            txt1.setText(str);
            Log.v("zms", str);
         }
        } catch (JSONException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } 
       }
       else if (msg.what==2)
       {
        Log.v("zms","使用httpurlconnection返回的json");
        try {
         JSONArray jsonArray = new JSONArray(String.valueOf(msg.obj));
             txt1.setText(" ");
             str="urlconnect:";
         for (int i=0;i<jsonArray.length();i++)
         {
            JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i); 
             str=str+"第"+i+"个,devid:"+jsonObject2.getString("devid")+"维度:"+jsonObject2.getString("latitude")+" ";
            txt1.setText(str);
            Log.v("zms", str);
         }
        } catch (JSONException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } 
       }
       
       super.handleMessage(msg);
      }
         
        };
     
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      txt1=(TextView)findViewById(R.id.textView1);
      
     
      
      //最简单 的 直接一个对象
      btn2=(Button)findViewById(R.id.button2);
      btn2.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        txt1.setText("");
        str="";
        try {
         // {"username":"zms",age:23,"addr","from china"};
         String json="{"username":"zms","age":43,"addr":"江西省高安市村前镇"}";
            JSONObject jsonObject2 =new JSONObject(json);
             str="名字:"+jsonObject2.getString("username")+"年薪:"+jsonObject2.getString("age")+jsonObject2.getString("addr")+" ";
            txt1.setText(str);
            Log.v("zms", str);
          
        } catch (JSONException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } 
         
       }
      });
      
      //对象里有数组
      btn3=(Button)findViewById(R.id.button3);
      btn3.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        txt1.setText("");
        str="";
        try {
         //{"username":"zms",age:11,"jicheng":[{"zhengshu":"PMP","date":"2011年"},{"zhengshu":"信息系统项目管理师","date","2012年"}],"addr":"江西"}
         // 这种也属于 对象里有数组   {"json":[{"username":"zms","date":"2011年"},{"username":"ivy","date","2012年"}]}
    String json= "{"username":"张木生",age:11,"jicheng":[{"zhengshu":"PMP","date":"2011年"},{"zhengshu":"信息系统项目管理师","date":"2012年"}],"addr":"江西"}";
          
                JSONObject jsonObject2 =new JSONObject(json);
             str="名字:"+jsonObject2.getString("username");
             str=str+"工龄:"+jsonObject2.getString("age")+"证书:";
             JSONArray jsonArray = jsonObject2.getJSONArray("jicheng"); 
             for (int i=0;i<jsonArray.length();i++)
             {
              JSONObject jsonObjectSon= (JSONObject)jsonArray.opt(i); 
              str=str+jsonObjectSon.getString("zhengshu")+"年份:"+jsonObjectSon.getString("date");
             }
             str=str+"籍贯"+jsonObject2.getString("addr");
              txt1.setText(str);
             Log.v("zms", str);
          
        } catch (JSONException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } 
         
       }
      });
      
      //直接一个数组 
      btn4=(Button)findViewById(R.id.button4);
      btn4.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        Log.v("zms","响应4");
        txt1.setText("");
        str="";
        //  返回的字符串 直接是个数组
        // [{"devid":"1234567800","latitude":"29.4963","longitude":"116.189"},{"devid":"1234567832","latitude":"29.4943","longitude":"1161.129"}]
     String json="[{"devid":"1234567800","latitude":"29.4963","longitude":"116.189"},{"devid":"1234567832","latitude":"29.4943","longitude":"1161.129"}]";
         try {
          JSONArray jsonArray = new JSONArray(json);
          for (int i=0;i<jsonArray.length();i++)
          {
             JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i); 
        str=str+"第"+i+"个,devid:"+jsonObject2.getString("devid")+"维度:"+jsonObject2.getString("latitude")+"经度:"+jsonObject2.getString("longitude")+" ";
            
          }
           txt1.setText(str);
            Log.v("zms", str);
         } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
         } 
         
         
       }
      });
      
      //数组里有数组
        btn5=(Button)findViewById(R.id.button5);
        btn5.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
           
          txt1.setText("");
          str="";
          //  返回的字符串 直接是个数组
       /*   [
          {"devid":"1234567800","gps":[{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189"},{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189" }],"devname":"赣01"},
           {"devid":"1234567800","gps":[{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189"},{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189" }],"devname":"赣92"},
           {"devid":"1234567800","gps":[{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189"},{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189" }],"devname":"赣43"},
           ], */
       String json="["+
                   "{"devid":"1234567800","gps":[{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189"},{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189" }],"devname":"赣01"},"+
                   " {"devid":"1234567800","gps":[{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189"},{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189" }],"devname":"赣92"},"+
                   " {"devid":"1234567800","gps":[{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189"},{"time":"2014-11-12","latitude":"29.4963","longitude":"116.189" }],"devname":"赣43"}"+
                   "]";
           try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i=0;i<jsonArray.length();i++)
            {
              String tpstr="";
               JSONObject jsonObject5 = (JSONObject)jsonArray.opt(i); 
               str=str+"第"+i+"条船,设备号devid:"+jsonObject5.getString("devid");
               JSONArray jsonArray5 = jsonObject5.getJSONArray("gps"); 
               for (int j=0;j<jsonArray5.length();j++)
               {
                JSONObject jsonOb5Son=(JSONObject)jsonArray5.opt(j);
                 tpstr="采集时间:"+jsonOb5Son.getString("time")+"维度"+jsonOb5Son.getString("latitude")+"经度:"+jsonOb5Son.getString("longitude");
                
               }
               str=str+tpstr;
           
              
            }
             txt1.setText(str);
              Log.v("zms", str);
           } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           } 
           
           
         }
        }); 
        
        //httpclient访问网络返回json
        btn6=(Button)findViewById(R.id.button6);
        btn6.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
          txt1.setText("");
           /*从安卓3.0以后,就不允许在主线程中直接访问网络,必须在子线程中访问
           访问后要修改主线程的UI,需要使用handler通信*/
           accessThread1 mythread1=new accessThread1();
           mythread1.start();
         }
        });
        
        //httpurlconnection访问网络返回json
        btn7=(Button)findViewById(R.id.button7);
        btn7.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
          txt1.setText("");
           /*从安卓3.0以后,就不允许在主线程中直接访问网络,必须在子线程中访问
           访问后要修改主线程的UI,需要使用handler通信*/
           accessThread2 mythread2=new accessThread2();
           mythread2.start();
         }
        });
      
     }
     
     class   accessThread1 extends Thread{
     
      @Override
      public void run() {
     
       Log.v("zms","线程accessThread开始");
       Message msg1=handler.obtainMessage();
       msg1.what=1;
       msg1.obj=util.getHttpJsonByhttpclient(baseUrl);
       handler.sendMessage(msg1);
       super.run();
      }
      
     }
     
     class   accessThread2 extends Thread{
       
      @Override
      public void run() {
     
       Log.v("zms","线程accessThread2开始");
       
       Message msg2=handler.obtainMessage();
       msg2.what=2;
       msg2.obj=util.getHttpJsonByurlconnection(baseUrl);
       handler.sendMessage(msg2);
       super.run();
      }
      
     }
     
     

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }

    }

    -------------------------------------------------------------------------------------------------------------------------------

    layout XMl文件

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context=".MainActivity" >
     
     <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
        
        <Button
            android:id="@+id/button2"
                 android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="直接一个对象" />

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="对象里有数组" />

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="直接一个数组" />
        
            <Button
            android:id="@+id/button5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="数组里还有数组" />
            
            
        <Button
            android:id="@+id/button6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="httpclient获取json" />
        
         <Button
            android:id="@+id/button7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="httpurlconnection获取json" />
        
           
    </LinearLayout>

    公共服务类  util  里面2个静态方法 用来 返回 json 字符串

    package com.example.json;

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

    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
     
    import android.util.Log;

    public class util {
     
     public static String  getHttpJsonByhttpclient(String  fromurl)
     {
         
       try{
             Log.v("zms","使用httget");
                HttpGet geturl=new HttpGet(fromurl);
                DefaultHttpClient httpclient=new DefaultHttpClient();
             HttpResponse response=httpclient.execute(geturl);
              Log.v("zms","响应码"+response.getStatusLine().getStatusCode());
               if (response.getStatusLine().getStatusCode()==200)
               {
                 
                   String returnStr=EntityUtils.toString(response.getEntity(),"utf-8");
                Log.v("zms","返回值"+returnStr);
                   return returnStr;
               } else
               {
                Log.v("zms","访问网络返回数据失败,错误码:"+response.getStatusLine().getStatusCode());
               }
           
            } 
            catch(IOException e)
            {
             e.printStackTrace();
            } 
       return null;
      
     }
     
     public static String  getHttpJsonByurlconnection(String fromurl)
     {
      try
      {
       Log.v("zms","使用httpurlconnection");
       ByteArrayOutputStream os=new ByteArrayOutputStream();
       byte[] data =new byte[1024];
       int len=0; 
       URL url=new URL(fromurl);
       HttpURLConnection conn=(HttpURLConnection)url.openConnection();
       InputStream in=conn.getInputStream();
       while ((len=in.read(data))!=-1)
       {
        os.write(data,0,len);
       }
       in.close();
       return new String(os.toByteArray());
      } catch (Exception e)
      {
       e.printStackTrace();
      }
     
      return null;
     }

    }

  • 相关阅读:
    游览器保存密码和自动填充密码的困惑 (browser save password and auto fill password )
    SQL basic
    ui router digest 10 time
    HttpCookie
    web api 2 学习笔记 (OData Batch request)
    $provide.decorator
    Entity Framewor 学习笔记 (碎碎的东西)
    生活类App原型制作分享-AnyList
    2019年网页设计趋势前瞻,先睹为快!
    Mockplus3.5.0.1新增标注功能
  • 原文地址:https://www.cnblogs.com/huoshenmanbu/p/4765556.html
Copyright © 2020-2023  润新知