澳门新浦京娱乐场网站-www.146.net-新浦京娱乐场官网
做最好的网站

怎样在Swift3中获得Json包的剧情

我想在这个帖子里面总结两个问题:一个是通过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 的 请求 URL 形式(我这里仅获取关键字搜索视频列表)是

youtube API 的 请求 URL 形式(我这里仅获取关键字搜索视频列表)是

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的常用包——Fastjson

Fastjson是一个Java语言编写的JSON处理器,由阿里巴巴公司开发。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。下面来介绍一下Fastjson常用类。

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

Fastjson 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。

怎样在Swift3中获得Json包的剧情。使用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 表示数字的占位符、# 也表示 数字,但是不显示前导零

}

第二层

对于 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.146.net,转载请注明出处:怎样在Swift3中获得Json包的剧情