zoukankan      html  css  js  c++  java
  • Android Json 解析

    方法一 使用API解析

    json:

    {"beaconid":"2397","state":"01","userid":"90"}

    获取json的方法

     private void sendRequestWithHttpClient(){
                    new Thread(new Runnable() {
                      @Override
                      public void run() {
    
                              
                              try {
                                     // HttpClient对象
    
                                  HttpClient httpClient = new DefaultHttpClient();
                                     // HttpGet对象
                                  HttpGet httpGet = new HttpGet("http://192.168.0.103/test.json");
                                  HttpResponse httpResponse = httpClient.execute(httpGet);
                                  if (httpResponse.getStatusLine().getStatusCode() == 200) {
                                      HttpEntity entity = httpResponse.getEntity();
                                      // 取得返回的数据
                                      String response = EntityUtils.toString(entity, "utf-8");
    //解析json parseJSONWithJSONObject(response); } }
    catch (IOException e) { e.printStackTrace(); } } }).start(); }

    解析json的方法

     private void parseJSONWithJSONObject (String jsonData){
            try {
                JSONObject jsonObj = new JSONObject(jsonData);
                String beaconid = jsonObj.getString("beaconid");
                String state = jsonObj.getString("state");
                String uid = jsonObj.getString("userid");
                Log.d("beaconid","beaconid is"+" "+beaconid);
                Log.d("state","state is"+ " "+state);
                Log.d("userid","userid is"+ " "+uid);
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    最后在MainActivity 调用 sendRequestWithHttpClient() 方法;

    记得在AndroidMainfest.xml

    <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.hardware.sensor.accelerometer" />


  • 相关阅读:
    <%# %>数据绑定
    BUTTON在界面上位置的移动
    双击树节点,将其添加到ListBar中
    关于魔方的故事 来源:未知
    xml做TreeView
    子父窗体
    word中,文档更改标记
    Ogre中实现 几何面正反面不同纹理贴图
    利用模板化的空闲块列表克服内存碎片问题
    window平台下 实时高效打印其他窗口,并作为D3D纹理使用
  • 原文地址:https://www.cnblogs.com/stuart/p/4502968.html
Copyright © 2011-2022 走看看