澳门新萄京官方网站-www.8455.com-澳门新萄京赌场网址

如何在Swift3中获取Json包的内容

2019-07-14 作者:www.8455.com   |   浏览(84)

自己想在那些帖子里面计算七个难题:三个是透过ReST获取Json的言语,那么些比较简单

自个儿想在这一个帖子里面计算多少个难题:叁个是因而ReST获取Json的话语,那个比较轻巧

前面叁个调用API的时候大非常多都以利用json作为数据的回来格式,json也足以当作一种格式来进展数量存款和储蓄,也给大家提供了一种体系化的艺术。
  Json使用花括号{}包括的键值对结构,key必须是string类型,value为任何基本项目或数据结构。规范的json基本数据类型有string、number、true、false、null;
  Json有三种数据结构:1.Map,也称为对象:{'key1':'value1','key2':'value2'} 2.Array:['arr1','arr2','arr3']。也正是说全数JSON对象都以要以那么些情势表示,

Json file

Project address: QuakeReport-github

另一个是哪些将Json包一层一层转存为字典,并最终通过keyword: String获得所需内容的章程

另贰个是何等将Json包一层一层转存为字典,并最后经过keyword: String获得所需内容的方法

澳门新萄京官方网站 1

About this course

Build a earthquake app.

  1. Where to find the earthquake data.
  2. API: application programming interface.
  3. Earthquake data from the USGS

废话不说,来看代码

废话不说,来看代码

  要专注,上边的事例中,null表示叁性子质或因素未有值,而''代表的是空字符串。
  JSON字符串与JSON对象的区分,上边说一下:

How to describe earthquake

magnitude, epicenter, depth, date, and so on.

先是是服务器再次来到的Json情势,这里以youtube API为例,因为google做的Json包很正规(都以 String: String 恐怕 String: Int)

首先是服务器重返的Json形式,这里以youtube API为例,因为google做的Json包很正规(都以 String: String 也许 String: Int)

  • JSON对象是直接能够动用JQuery操作的格式,和js中的对象一样,能够用对象(类名)点出属性(方法)。

Json: packaged data

USGS website

GEOJson Summary Format

API documentation

youtube API 的 诉求 U景逸SUVL 格局(小编那边仅收获重要字寻找录像列表)是

youtube API 的 央求 UPRADOL 方式(小编那边仅收获首要字寻觅摄像列表)是

var str2 = { "name": "haorooms", "sex": "man" };

URL format

In the API Documentation we can see that the URL format: https://earthquake.usgs.gov/fdsnws/event/1/[METHOD[?PARAMETERS]]. There are many Methods we can use. For example, we use query method to submit a data request. query method has many parameters to indicate the query time and other search condition.

This will return a GEOJson file.

https://www.googleapis.com/youtube/v3/search?part=snippet&q=录制关键字&type=video&key=你的API Key

https://www.googleapis.com/youtube/v3/search?part=snippet&q=摄像关键字&type=video&key=你的API Key

  • JSON字符串仅仅只是三个字符串,叁个整机,不截取的话不可能收取当中蕴藏的多寡,不可能直接使用,除非你只想alert()他;

Json format

GEOJson Summary Format

其间,摄像关键字比方 minecraft

里面,摄像关键字举例 minecraft

浅析与转变Json的常用包——法斯特json

法斯特json是贰个Java语言编写的JSON管理器,由Alibaba公司开拓。它应用一种“假定有序高效同盟”的算法,把JSON Parse的属性升高到极致,是近年来Java语言中最快的JSON库。上边来介绍一下法斯特json常用类。

Display Earthquake information

After import the code from github, we do some changes. The app will looks like below.

澳门新萄京官方网站 2

API Key 形如 AIzaSyDDqTGpVR7jxeozoOEjH6SLaRdw0YY-HPQ

API Key 形如AIzaSyDDqTGpVR7jxeozoOEjH6SLaRdw0YY-HPQ

(1)com.alibaba.fastjson.JSON

法斯特json API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都得以在JSON类上的静态方法间接到位。

Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray 
JSONObject parseObject(String text); // 把JSON文本parse成JSONObject 
T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean 
JSONArray parseArray(String text); // 把JSON文本parse成JSONArray 
List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合 
String toJSONString(Object object); // 将JavaBean序列化为JSON文本 
String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本 
Object toJSON(Object javaObject); //将JavaBean转换为JSONObject或者JSONArray

【示例】

protected JSONObject wrapHint(Object o) {
   return o == null?null:
      (o instanceof JSONObject?(JSONObject)o:
        (o instanceof String?JSON.parseObject("{'.':'"   (String)o   "'}"):
           null));
}

Add Earthquake class

We need a class to store the information of an earthquake, including magnitude, Location and date.

// a float number to store the magnitude.
    private float mMagnitude;
    // a String value to store the location
    private String mLocation;
    // a String value to store the date in the format "Feb 2, 2016"
    private String mDate;

In this class, There should be a constructor to set the value of the three variables.

/**
     *
     * @param magnitude the magnitude of the earthquake
     * @param location the location of the earthquake, maybe a city name
     * @param date the date of the earthquake in the format "Feb 2, 2016"
     */
    public Earthquake(float magnitude, String location, String date) {
        mMagnitude = magnitude;
        mLocation = location;
        mDate = date;
    }

Then, We have the getter method to get the value.

 /**
     *
     * @return return magnitude
     */
    public float getmMagnitude() {
        return mMagnitude;
    }

    /**
     *
     * @return return date
     */
    public String getmDate() {
        return mDate;
    }

    /**
     *
     * @return return location
     */
    public String getmLocation() {
        return mLocation;
    }

其回到的Json包格局为

其归来的Json包格局为

(2)JSONObject类

JSONObject组织形式是贰个键值对,事实上,JSONObject是贰个Map。剖判成功后,倘诺是Java内置对象,能够直接调用相应的点子取得值,例如public Integer getInteger(String key);假诺不是放到对象,能够调用public JSONObject getJSONObject(String key)来读取对象。借使仍然数组,能够调用public JSONArray getJSONArray(String key)。
  JSONObject能够分析Map、JavaBean对象等,让我们一齐来看一下JSONObject的构造方法。

    private static final int DEFAULT_INITIAL_CAPACITY = 16;
    private final Map<String, Object> map;
    public JSONObject() {
        this(16, false);
    }

    public JSONObject(Map<String, Object> map) {
        this.map = map;
    }

    public JSONObject(boolean ordered) {
        this(16, ordered);
    }

    public JSONObject(int initialCapacity) {
        this(initialCapacity, false);
    }

    public JSONObject(int initialCapacity, boolean ordered) {
        if(ordered) {
           //根据初始化容量初始化map
            this.map = new LinkedHashMap(initialCapacity);
        } else {
            this.map = new HashMap(initialCapacity);
        }
    }

不过JSONObject没法分析类似于HashMap<String,JSONObject>和HashMap<String, HashMap<String, Object>>的Map,那是因为JSONObject只认未有泛型的HashMap。

使用JSONObject构建json

JSONObject person = new JsonObject();
try{
    person.put("namr",ada);
    person.put("age",12);
    person.put("major",new String[]{"理发","挖掘机"});
    //print
    System.out.println(person.toString());
}catch(JSONException e){
}

使用Map构建json

Map<String,Object> person = new HashMap<String,Object>();
person.put("namr",ada);
person.put("age",12);
person.put("major",new String[]{"理发","挖掘机"});
//print
System.out.println(new JSONObject(person).toString());

使用JavaBean构建json

Person person = new Person();
person.setName(ada);
person.setAge(12);
person.setMajor(new String[]{"理发","挖掘机"});
//print
System.out.println(new JSONObject(person));

从文件中读取json

public static void main(String args[])throws IOException,JSONException{
     File file = new File(//json文件路径);
     String content = FileUtils.readFileToString(file);
     JSONObject jsonObject = new JsonObject(content);
     //从文件读取json判断null
     if(jsonObject.isNull("name")){
            System.out.println("姓名是" jsonObject.getString("name"));
     }
     System.out.println("年龄是" jsonObject.getDouble("age"));
     System.out.println("有没有女朋友" jsonObject.getBoolean("has_girlFriend"));
     JSONArray majorArray = jsonObject.getJSONArray("major");
     for(int i=0;i<majorArray.length();i  ){
          String m = (String)majorArray.get(i);
          System.out.println("专业-" (i 1) m);
     }
}

从JSONObject获取keySet

String string = "{key_1:123, key_2:234, key_3:567}";
JSONObject json= JSONObject.fromObject(string);
Set<String> set = json.keySet();
for(String key : set){
     System.out.println("key==" key);
}

Add EarthquakeAdapter

Then, we need the Adapter to show the information on the screen.

create the file EarthquakeAdapter.java.

{
 "kind": "youtube#searchListResponse",
 "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/dJyYeiv8CbvQiayof_7MqRQOSi8"",
 "nextPageToken": "CAUQAA",
 "regionCode": "AU",
 "pageInfo": {
  "totalResults": 1000000,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/ey6kUbVRRdmcLIPpklkbtxDp_-o"",
   "id": {
    "kind": "youtube#video",
    "videoId": "XgdgO5UzdR4"
   },
   "snippet": {
    "publishedAt": "2016-11-27T12:00:01.000Z",
    "channelId": "UCUVa51UA_690sEKyRbHb-5A",
    "title": "5 Werewolves Caught on Camera & Spotted In Real Life!",
    "description": "5 Werewolves Caught on Tape & Spotted In Real Life! Description: Myths and stories of humans with the ability to transform into animals exist across all human ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/XgdgO5UzdR4/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/XgdgO5UzdR4/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/XgdgO5UzdR4/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Top 5s Finest",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/LKJrjJEelN2h1v58M533Dwv_fjs"",
   "id": {
    "kind": "youtube#video",
    "videoId": "KUS0454UUDM"
   },
   "snippet": {
    "publishedAt": "2016-08-03T10:16:33.000Z",
    "channelId": "UC0rzsIrAxF4kCsALP6J2EsA",
    "title": "MAIN-MAIN: WEREWOLF",
    "description": "Yang mau liat tutorial cara mainnya, klik di sini: https://youtu.be/ShGULqRjLMk.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/KUS0454UUDM/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/KUS0454UUDM/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/KUS0454UUDM/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Raditya Dika",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/8qIl76CAeB__wn-Sd_g4pik1XT0"",
   "id": {
    "kind": "youtube#video",
    "videoId": "fScsIQ8wgNo"
   },
   "snippet": {
    "publishedAt": "2016-10-02T22:21:35.000Z",
    "channelId": "UCNUohh38MTkgY4xKpFeVGmQ",
    "title": "Werewolf Scenes - My Favorite Transformation HD",
    "description": "Werewolf Scenes - My Favorite Transformation HD.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/fScsIQ8wgNo/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/fScsIQ8wgNo/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/fScsIQ8wgNo/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "ENJOY PLEASE",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/SByO_v4iInfFZ5GUe2xJUYXIWh4"",
   "id": {
    "kind": "youtube#video",
    "videoId": "ShGULqRjLMk"
   },
   "snippet": {
    "publishedAt": "2016-08-03T10:13:33.000Z",
    "channelId": "UC0rzsIrAxF4kCsALP6J2EsA",
    "title": "TUTORIAL: MAIN WEREWOLF",
    "description": "Ini adalah video tutorial untuk main werewolf. Untuk melihat video permainannya, bisa klik di sini: https://youtu.be/KUS0454UUDM.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/ShGULqRjLMk/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/ShGULqRjLMk/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/ShGULqRjLMk/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Raditya Dika",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/NjscIZ4D3C-FDPsnBKe-j5tslrE"",
   "id": {
    "kind": "youtube#video",
    "videoId": "MI1Yi2AUVAc"
   },
   "snippet": {
    "publishedAt": "2016-09-09T07:27:23.000Z",
    "channelId": "UCNUohh38MTkgY4xKpFeVGmQ",
    "title": "Vampire vs Werewolf Fight Scene HD - Van Helsing - Vampire vs Lycan Wolf",
    "description": "Vampire vs Werewolf Fight Scene HD - Van Helsing - Vampire vs Lycan Wolf.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/MI1Yi2AUVAc/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/MI1Yi2AUVAc/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/MI1Yi2AUVAc/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "ENJOY PLEASE",
    "liveBroadcastContent": "none"
   }
  }
 ]
}
---------------------------------------------------------------------------------------------------------------------
第 0 层 
{  }
第一层
{  
   "kind":"youtube#searchListResponse",
   "etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/g4lxZZLl2WXJPiISOtol-Vf33d8"",
   "nextPageToken":"CAUQAA",
   "regionCode":"US",
   "pageInfo":{  },
   "items":[  ]
}
第二层
对于 pageInfo 
{  
      "totalResults":1000000,
      "resultsPerPage":5
}
对于 items (注意那个中括号)
[  [
      {  
         "kind":"youtube#searchResult",
         "etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/ey6kUbVRRdmcLIPpklkbtxDp_-o"",
         "id":{  },
         "snippet":{  }
      },
      {  
         "kind":"youtube#searchResult",
         "etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/LKJrjJEelN2h1v58M533Dwv_fjs"",
         "id":{  },
         "snippet":{  }
      },
      {  
         "kind":"youtube#searchResult",
         "etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/8qIl76CAeB__wn-Sd_g4pik1XT0"",
         "id":{  },
         "snippet":{  }
      },
      {  
         "kind":"youtube#searchResult",
         "etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/SByO_v4iInfFZ5GUe2xJUYXIWh4"",
         "id":{  },
         "snippet":{  }
      },
      {  
         "kind":"youtube#searchResult",
         "etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/NjscIZ4D3C-FDPsnBKe-j5tslrE"",
         "id":{  },
         "snippet":{  }
      }
   ]
这就是说,中括号里面的内容实际上是一个数组,这个数组有五个元素。

第三层
以其中一个元素为例
对于 id
{  
            "kind":"youtube#video",
            "videoId":"XgdgO5UzdR4"
}
对于 snippet
{  
            "publishedAt":"2016-11-27T12:00:01.000Z",
            "channelId":"UCUVa51UA_690sEKyRbHb-5A",
            "title":"5 Werewolves Caught on Camera & Spotted In Real Life!",
            "description":"5 Werewolves Caught on Tape & Spotted In Real Life! Description: Myths and stories of humans with the ability to transform into animals exist across all human ...",
            "thumbnails":{  },
            "channelTitle":"Top 5s Finest",
            "liveBroadcastContent":"none"
 }
第四层
对于 thumbnails
{  
               "default":{  },
               "medium":{  },
               "high":{  }
}
第五层
对于 default 
{  
                  "url":"https://i.ytimg.com/vi/XgdgO5UzdR4/default.jpg",
                  "width":120,
                  "height":90
}
其它两个类似

至此Json 包解析完毕。
然后附上代码。首先是ReST请求部分

{ "kind": "youtube#searchListResponse", "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/dJyYeiv8CbvQiayof_7MqRQOSi8"", "nextPageToken": "CAUQAA", "regionCode": "AU", "pageInfo": {  "totalResults": 1000000,  "resultsPerPage": 5 }, "items": [  {  "kind": "youtube#searchResult",  "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/ey6kUbVRRdmcLIPpklkbtxDp_-o"",  "id": {    "kind": "youtube#video",    "videoId": "XgdgO5UzdR4"  },  "snippet": {    "publishedAt": "2016-11-27T12:00:01.000Z",    "channelId": "UCUVa51UA_690sEKyRbHb-5A",    "title": "5 Werewolves Caught on Camera & Spotted In Real Life!",    "description": "5 Werewolves Caught on Tape & Spotted In Real Life! Description: Myths and stories of humans with the ability to transform into animals exist across all human ...",    "thumbnails": {    "default": {      "url": "",      "width": 120,      "height": 90    },    "medium": {      "url": "",      "width": 320,      "height": 180    },    "high": {      "url": "",      "width": 480,      "height": 360    }    },    "channelTitle": "Top 5s Finest",    "liveBroadcastContent": "none"  }  },  {  "kind": "youtube#searchResult",  "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/LKJrjJEelN2h1v58M533Dwv_fjs"",  "id": {    "kind": "youtube#video",    "videoId": "KUS0454UUDM"  },  "snippet": {    "publishedAt": "2016-08-03T10:16:33.000Z",    "channelId": "UC0rzsIrAxF4kCsALP6J2EsA",    "title": "MAIN-MAIN: WEREWOLF",    "description": "Yang mau liat tutorial cara mainnya, klik di sini: .",    "thumbnails": {    "default": {      "url": "",      "width": 120,      "height": 90    },    "medium": {      "url": "",      "width": 320,      "height": 180    },    "high": {      "url": "",      "width": 480,      "height": 360    }    },    "channelTitle": "Raditya Dika",    "liveBroadcastContent": "none"  }  },  {  "kind": "youtube#searchResult",  "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/8qIl76CAeB__wn-Sd_g4pik1XT0"",  "id": {    "kind": "youtube#video",    "videoId": "fScsIQ8wgNo"  },  "snippet": {    "publishedAt": "2016-10-02T22:21:35.000Z",    "channelId": "UCNUohh38MTkgY4xKpFeVGmQ",    "title": "Werewolf Scenes - My Favorite Transformation HD",    "description": "Werewolf Scenes - My Favorite Transformation HD.",    "thumbnails": {    "default": {      "url": "",      "width": 120,      "height": 90    },    "medium": {      "url": "",      "width": 320,      "height": 180    },    "high": {      "url": "",      "width": 480,      "height": 360    }    },    "channelTitle": "ENJOY PLEASE",    "liveBroadcastContent": "none"  }  },  {  "kind": "youtube#searchResult",  "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/SByO_v4iInfFZ5GUe2xJUYXIWh4"",  "id": {    "kind": "youtube#video",    "videoId": "ShGULqRjLMk"  },  "snippet": {    "publishedAt": "2016-08-03T10:13:33.000Z",    "channelId": "UC0rzsIrAxF4kCsALP6J2EsA",    "title": "TUTORIAL: MAIN WEREWOLF",    "description": "Ini adalah video tutorial untuk main werewolf. Untuk melihat video permainannya, bisa klik di sini: .",    "thumbnails": {    "default": {      "url": "",      "width": 120,      "height": 90    },    "medium": {      "url": "",      "width": 320,      "height": 180    },    "high": {      "url": "",      "width": 480,      "height": 360    }    },    "channelTitle": "Raditya Dika",    "liveBroadcastContent": "none"  }  },  {  "kind": "youtube#searchResult",  "etag": ""uQc-MPTsstrHkQcRXL3IWLmeNsM/NjscIZ4D3C-FDPsnBKe-j5tslrE"",  "id": {    "kind": "youtube#video",    "videoId": "MI1Yi2AUVAc"  },  "snippet": {    "publishedAt": "2016-09-09T07:27:23.000Z",    "channelId": "UCNUohh38MTkgY4xKpFeVGmQ",    "title": "Vampire vs Werewolf Fight Scene HD - Van Helsing - Vampire vs Lycan Wolf",    "description": "Vampire vs Werewolf Fight Scene HD - Van Helsing - Vampire vs Lycan Wolf.",    "thumbnails": {    "default": {      "url": "",      "width": 120,      "height": 90    },    "medium": {      "url": "",      "width": 320,      "height": 180    },    "high": {      "url": "",      "width": 480,      "height": 360    }    },    "channelTitle": "ENJOY PLEASE",    "liveBroadcastContent": "none"  }  } ]}

(3)JSONArray

JSONArray用来寄存在JSON数组。分析成功后,如若是Java对象,能够调用相应措施拿到值,举个例子public Integer getInteger(int index)。如若不是放置对象,能够调用public JSONObject getJSONObject(int index)来读取对象。

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

public class ParseJSONObject {

    public static void main(String args[]){
        String json = "[{"id":1,"type":"cycle","attribute":{"center":"(10.4, 123.345)", "radius":67.4}},{"id":2,"type":"polygon","attribute":[{"vertex":"(10.4, 133.345)"}, {"vertex":"(10.4, 143.345)"}]}]";
        JSONArray array = JSON.parseArray(json);
        System.out.println(array.getJSONObject(0).getJSONObject("attribute").get("center"));
        System.out.println(array.getJSONObject(1).getJSONArray("attribute").getJSONObject(1).get("vertex"));
    }
}

输出为:
(10.4, 123.345)
(10.4, 143.345)

JSONArray实际上是一个List,让大家来看一下它的构造方法:

   private final List<Object> list;
   public JSONArray() {
        this.list = new ArrayList(10);
    }

    public JSONArray(List<Object> list) {
        this.list = list;
    }

    public JSONArray(int initialCapacity) {
        this.list = new ArrayList(initialCapacity);
    }

所以我们得以像使用List同样接纳JSONArray:

public <T> T[] toArray(T[] a)    //把JSONArray变成数组
public boolean add(Object e)     //向JSONArray添加元素
public boolean contains(Object o)
public Iterator<Object> iterator()
public void setComponentType(Type componentType)
public Type getComponentType()   //取得一个数组的Class对象,非数组类型无法通过getComponentType()获取到相应的 Class 对象,如char[].class 调用此方法得到的就是char,但是char.class得到的就是nnull

Constructor

We use our custom constructor because we use our list_item view.

/**
     * This is our custom constructor,
     * The context is used to inflate the layout file,
     * and the list is the data we want to populate into the lists.
     * @param context The current context. Used to inflate the layout file.
     * @param earthquakes A List of Earthquake objects to display in a list
     */
    public EarthquakeAdapter(Activity context, ArrayList<Earthquake> earthquakes){
        // the second parameter is 0 to indicate we will use our custom list item view to show.
        super(context, 0, earthquakes);
    }

澳门新萄京官方网站 3


Json的缺点

①JSON是文本,它的频率不高

  • 具有的数据都以字符方式的JSON要求转移管理。
  • 每种值在各个文书档案中都带有其键名称,须要更加多的囤积和管理。
  • 同意表示复杂的布局,导致运维时支付。

举例将JSON作为一种数据库的多少格式时,数据库要费用相当多代价,因为每一条记下里面键和值都要存,何况每一趟查询都要进行拍卖。那将意味着:

  • 数据库引擎必须知道每种文书档案的方式并处理它们,实际不是管理不奇怪元组和性能(行和列)。
  • 必须剖判和管理JSON中每一个键值的数据类型
  • JSON或者是XML的二个精简的版本,但它依旧非常壮实大。

就算如此说JSON作为一种数据库的数额格式的频率不高,可是首要如故看您数据库引擎怎么落到实处,索引系统怎么落到实处。举个例子Mongodb的存款和储蓄格式是BSON,BSON是一种类JSON的二进制格局的蕴藏格式,简称Binary JSON。然而Mongodb的频率照旧异常高的。

②JSON未有可实行组织,毫无数据质量可言
  JSON在数据库中不须要数据结构,由此数据品质差。自从JSON数据库不需求另外组织,不管是蓄意依旧无意,应用程序都能够插入任何格式的数据流,只要这么些多少是实用的JSON。

getView()

  1. Inflate the view
  2. get data using getItem(position)
  3. set data
然后是Json解析部分

第 0 层

Json

GEOJson is a special flavor of JSON.

Json: JavaScript Object Notation

Brace, Key Value pairing

澳门新萄京官方网站 4

{}

Parsing Json in Android

Class JSONObject

Example:
Json file:

{
    "candies":[
        {
            "name":"Jelly Beans",
            "count":10
        }
    ]
}

Android code:

String candyJson = "{"candies":[{"name":"Jelly Beans","count":10}]}";

JSONObject root = new JSONObject(candyJson);

JSONArray candiesArray = root.getJSONArray("candies");

JSONObject firstCandy = candiesArray.getJSONObject(0);

String name = firstCandy.getString("name");
int count = firstCandy.getInt("count");

Android provides four different classes to manipulate JSON data. JSONArray, JSONObject, JSONStringer and JSONTokenizer.

只解释Json解析部分。
我现在的目的是取出四个key值:视频的title、description、thumbnail default url 还有 videoId
过程是这样:
根据我上面的分析,从第一层开始(第 0 层不算)每层都建立[String: AnyObject]字典或数组(根据Json那一层的结构而定)。在最后一层只有String内容的时候,也可以建立[String: String]字典(也就是idDict也可以建成[String: String]的,别的不可以。)
第一层 - resultDict 这个不能建成[String: String],因为pageInfo和items关键字对应的不是String,而是一个或多个子字典。
第二层 - 因为pageInfo里面的内容我不需要(如需要建字典),所以只有items对应的数组 -- itemsArray  (建数组因为items本身是五个元素组成的数组,在前面已经说明。)
第三层 - 对于 id -- idDict字典,这个可以建[String: AnyObject]也可以建[String: String](因为内容只有String,建AnyObject的话,就需要cast一下(as! String)。)
对于 snippet -- snippetDict字典,这个必须[String: AnyObject]
第四层 - thumbnailDict
第五层 - defaultDict,其它两个Key里面的信息不需要,如果需要,也可以建相应字典提取出来。
然后我建了一个每个元素都是[String: AnyObject]字典的Array,形如[[String: AnyObject]],用来储存我提取出来的四个keyword对应的信息。当然,这个数组建成[[String: String]]也是可以的。当时对这个代码理解还不深,属于半迷糊状态。

然后就大功告成。

第一层

JSON Elements

Str.No Component & description
1 Array: [] <p>In a JSON file, square bracket [] represents a JSON array
2 Objects: {} <p>In a JSON file, curly bracket {} represents a JSON object
3 Key <p>A JSON object contains a key that is just a string. Pairs of key/value make up JSON object.
4 Value <p>Each key has a value that could be string, integer or double, etc.

 

{

JSON Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it.

String in;
JSONObject reader = new JSONObject(in);
Str.No Method & description
1 get(String name) <p>This method just Returns the value but in the format of Object type.
2 getBoolean(String name) <p>This method returns the boolean value specified by the key.
3 getDouble(String name) <p>This method returns the double value specified by the key.
4 getInt(String name) <p>This method returns the integer value specified by the key
5 getLong(String name) <p>This method returns the long value specified by the key
6 length() <p>This method returns the number of name/value mappings in this object.
7 names() <p>This method returns an array containing the string names in this object.

"kind":"youtube#searchListResponse",

QuakeUtil.java

We create a java class QuakeUtil.java to do something for quake data.

"etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/g4lxZZLl2WXJPiISOtol-Vf33d8"",

Constructor

This util class is only directly accessed from the class name, so we need the private constructor. There will be no object.

/**
     * Create a private constructor because no one should ever create a {@link QueryUtils} object.
     * This class is only meant to hold static variables and methods, which can be accessed
     * directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
     */
    private QueryUtils() {
    }

"nextPageToken":"CAUQAA",

extractEarthquakes()

This method will Get the information from JSON and add the item to an ArrayList<Earthquake>.

/**
     * Return a list of {@link Earthquake} objects that has been built up from
     * parsing a JSON response.
     */
    public static ArrayList<Earthquake> extractEarthquakes() {

        // Create an empty ArrayList that we can start adding earthquakes to
        ArrayList<Earthquake> earthquakes = new ArrayList<>();

        // Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {

            // Parse the response given by the SAMPLE_JSON_RESPONSE string and
            // build up a list of Earthquake objects with the corresponding data.
            JSONObject root = new JSONObject(SAMPLE_JSON_RESPONSE);
            JSONArray features = root.getJSONArray("features");

            for (int i = 0; i < features.length(); i  ) {
                JSONObject earthquake = features.getJSONObject(i);
                JSONObject properties = earthquake.getJSONObject("properties");
                double mag = properties.getDouble("mag");
                String place = properties.getString("place");
                long time = properties.getLong("time");
                earthquakes.add(new Earthquake(Double.toString(mag), place, Long.toString(time)));
            }

        } catch (JSONException e) {
            // If an error is thrown when executing any of the above statements in the "try" block,
            // catch the exception here, so the app doesn't crash. Print a log message
            // with the message from the exception.
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }

        // Return the list of earthquakes
        return earthquakes;
    }

"regionCode":"US",

Show Earthquake date and time

In our app now, it shows the Unix time. We can use class SimpleDateFormat and Date to convert the time from Unix time to what we need.

Time format: yyyy-MM-dd HH:mm:ss:
y means year. yyyy: 2016
M means mounth. MM: 03
d means day. dd: 10
H hour
m minute
s second

  1. Create a Date class.
  2. Use class SimpleDateFormat to create a date formatter.
  3. Use this date formatter to format the Date object and output a String.
// time in ms format
long timeInMilliseconds = 1454124312220L;
// create Date object
Date dateObject = new Date(timeInMilliseconds);
// create the SimpleDateFormat object dateFormatter
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM DD, yyyy");
// Format the time
String dateToDisplay = dateFormatter.format(dateObject);

"pageInfo":{},

split the location and offset

The location we can get from JSON file is like "64km NNE of Tomatlan, Mexico" or "Pacific-AntarcticRidge"

We need to split the String to two part. "64km NNE of" and "Tomatlan, Mexico"

we use the method split of String.

private static final String LOCATION_SEPARATOR = "of";

...

String[] split_location = location.split("(?<="   LOCATION_SEPARATOR   ")");

We can judge if the String contains LOCATION_SEPARATOR to decide whether the String can be split.

if (location.contains(LOCATION_SEPARATOR)) {
            String[] split_location = location.split("(?<="   LOCATION_SEPARATOR   ")");
            locationOffsetToDisplay = split_location[0];
            locationToDisplay = split_location[1];
        } else {
            locationOffsetToDisplay = getContext().getString(R.string.near_the);
            locationToDisplay = location;
        }

"items":[]

Format the mag number

DecimalFormat

0 表示数字的占位符、#如何在Swift3中获取Json包的内容。 也象征 数字,然则不显得前导零

}

第二层

对于 pageInfo

{

"totalResults":1000000,

"resultsPerPage":5

}

对于 items (注意充足中括号)

[  [

{

"kind":"youtube#searchResult",

"etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/ey6kUbVRRdmcLIPpklkbtxDp_-o"",

"id":{},

"snippet":{}

},

{

"kind":"youtube#searchResult",

"etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/LKJrjJEelN2h1v58M533Dwv_fjs"",

"id":{},

"snippet":{}

},

{

"kind":"youtube#searchResult",

"etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/8qIl76CAeB__wn-Sd_g4pik1XT0"",

"id":{},

"snippet":{}

},

{

澳门新萄京官方网站,"kind":"youtube#searchResult",

"etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/SByO_v4iInfFZ5GUe2xJUYXIWh4"",

"id":{},

"snippet":{}

},

{

"kind":"youtube#searchResult",

"etag":""uQc-MPTsstrHkQcRXL3IWLmeNsM/NjscIZ4D3C-FDPsnBKe-j5tslrE"",

"id":{},

"snippet":{}

}

]那正是说,中括号里面的故事情节其实是八个数组,那一个数组有多少个元素。

第三层

以中间多少个要素为例

对于 id

{

"kind":"youtube#video",

"videoId":"XgdgO5UzdR4"

}对于 snippet

{

"publishedAt":"2016-11-27T12:00:01.000Z",

"channelId":"UCUVa51UA_690sEKyRbHb-5A",

"title":"5 Werewolves Caught on Camera & Spotted In Real Life!",

"description":"5 Werewolves Caught on Tape & Spotted In Real Life! Description: Myths and stories of humans with the ability to transform into animals exist across all human ...",

"thumbnails":{},

"channelTitle":"Top 5s Finest",

"liveBroadcastContent":"none"

}第四层

对于 thumbnails

{

"default":{},

"medium":{},

"high":{}

}第五层

对于 default

{

"url":"",

"width":120,

"height":90

}另外八个类似

由来Json 包分析完成。

接下来附上代码。首先是ReST央浼部分

澳门新萄京官方网站 5

下一场是Json分析部分

澳门新萄京官方网站 6

只解释Json剖析部分。

自身以后的目标是抽取七个key值:摄像的title、description、thumbnail default url 还应该有 videoId

经过是那般:

依赖小编上面的深入分析,从第一层初始(第 0 层不算)每层都创立[String: AnyObject]字典或数组(依照Json那一层的布局而定)。在终极一层唯有String内容的时候,也足以创制[String: String]字典(也正是idDict也足以建成[String: String]的,其他不可能。)

先是层 - resultDict 那么些无法建成[String: String],因为pageInfo和items关键字呼应的不是String,而是三个或多少个子字典。

其次层 - 因为pageInfo里面包车型客车源委自己不要求(如要求建字典),所以唯有items对应的数组 -- itemsArray  (建数组因为items自己是几个成分结合的数组,在前边早就认证。)

其三层 - 对于 id -- idDict字典,这几个能够建[String: AnyObject]也足以建[String: String](因为内容唯有String,建AnyObject的话,就必要cast一下(as! String)。)

对此 snippet -- snippetDict字典,那个必须[String: AnyObject]

第四层 - thumbnailDict

第五层 - defaultDict,别的三个Key里面包车型地铁音信无需,若是需求,也能够建相应字典提抽取来。

下一场本身建了一个各样成分都以[String: AnyObject]字典的Array,形如[[String: AnyObject]],用来囤积笔者领到出来的八个keyword对应的信息。当然,这一个数创设成[[String: String]]也是能够的。

本文由澳门新萄京官方网站发布于www.8455.com,转载请注明出处:如何在Swift3中获取Json包的内容

关键词: