1. 程式人生 > >關於安卓通過網路介面解析Json資料的簡單實現

關於安卓通過網路介面解析Json資料的簡單實現

1 MainActivity.java

package com.example.ms18.finalexam_2_20150861213;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    private EditText editText;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView = (TextView)this.findViewById(R.id.tv);

        editText = (EditText)this.findViewById(R.id.editId);

    }

    private Handler handler = new Handler(){

        public void  handleMessage(Message msg){

            super.handleMessage(msg);

            String data=(String)msg.obj;

            getJson(data);

        }

    };

    public void btnLook(View view){

        new Thread(runnable).start();

    }

    public void getJson(String data){

        String[] datas = data.split("",2);

        for(String s:datas){

            System.out.println("2111111111111111111111111111");

            System.out.println(s);

        }

        String newDtas = datas[1].substring(0,datas[1].lastIndexOf(""));

       // String weather1 = "["+newDtas+"]";

        //如果獲取到的json是資料,就直接用,如果不是,就拼接[],成為json陣列後再使用。

        String weather1 = newDtas;

        System.out.println("2111111111111111111111111111");

        System.out.println(newDtas);

        System.out.println(newDtas);

        try{

            JSONArray array = new JSONArray(weather1);

            for(int i =0; i<array.length();i++){

                System.out.println(array.length());

                JSONObject jsonObject = array.getJSONObject(i);

                String op = jsonObject.getString("op");

                String m = jsonObject.getString("m");

                String id = jsonObject.getString("id");

                String p= jsonObject.getString("p");

                System.out.println("2333333333333333");

                System.out.println("op:"+op +"m:"+m+"id:"+id+"p"+p);

                textView.setText("op:"+op +"  m:"+m+"  id:"+id+"  p"+p);

            }

        }

        catch(JSONException e){

            System.out.println(e.getMessage());

            e.printStackTrace();

        }

    }

    private Runnable runnable = new Runnable() {

        @Override

        public void run() {

            try {

                Message msg = new Message();

                StreamTools streamTools = new StreamTools();

                String id = editText.getText().toString();

                System.out.println(id);

                String urls="http://p.3.cn/prices/mgets?skuIds=J_"+id+"&type=1";

                //String urls=" http://pv.sohu.com/cityjson?ie=utf-8";

                String data = streamTools.getDataFromNetWork(urls);

                msg.obj = data;

                handler.sendMessage(msg);

            }

            catch (IOException e){

                e.printStackTrace();

            }

        }

    };

}

2 StreamTools.java

package com.example.ms18.finalexam_2_20150861213;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

/**

 * Created by ms28 on 2017-6-21.

 */

public class StreamTools {

    public String getDataFromNetWork(String uri)throws IOException{

        String data="";

        URL url =new URL(uri);

        HttpURLConnection connection=(HttpURLConnection)url.openConnection();

        connection.setConnectTimeout(4000);

        connection.setRequestMethod("GET");

        int code = connection.getResponseCode();

        if(code==200){

            InputStream inputStream = connection.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            int length;

            length = inputStream.read(buf);

            while (length>-1){

                baos.write(buf,0,length);

                length = inputStream.read(buf);

            }

            data = baos.toString();

            inputStream.close();

            baos.close();

            baos.flush();

        }

        return data;

    }

}

activity_main.xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    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"

    tools:context="com.example.ms18.finalexam_2_20150861213.MainActivity">

    <TextView

        android:id="@+id/tt"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="輸入IP:" />

        <EditText

            android:layout_width="300dp"

            android:layout_height="wrap_content"

            android:id="@+id/editId"

            android:layout_below="@+id/tt"/>

        <Button

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:id="@+id/btnLook"

            android:onClick="btnLook"

            android:text="檢視"

            android:layout_below="@id/editId"/>

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:id="@+id/tv"

            android:layout_below="@id/btnLook"/>

    </RelativeLayout>

AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.ms18.finalexam_2_20150861213">

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

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

            </intent-filter>

        </activity>

    </application>

    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>