Android中的JSON详细总结

发布时间:2026-09-28 17:55:35 浏览次数:2

下面是关于“Android中的JSON详细总结”的攻略。

什么是JSON

JSON(JavaScript Object Notation)是一种数据格式,常用于网络传输数据。它是在JavaScript中创建的对象,但现在已经成为一种独立的数据交换格式。

与XML相比,JSON更加简单、轻量级。在Android开发中,JSON也是比较流行的一种数据格式。

JSON的基本语法

JSON由键值对组成,每个键值对用逗号分隔。键值对的键(或属性)必须是一个字符串,值则可以是数字、字符串、布尔值、数组、对象或null等。

以下是一个例子:

{    "name": "Tom",    "age": 18,    "isMale": true,    "hobbies": ["Swimming", "Basketball"],    "address": {        "city": "Beijing",        "street": "Chaoyang Road"    },    "phoneNumbers": null}

在这个例子中,我们可以看到:

  • name和isMale是字符串类型的键值对;
  • age是数字类型的键值对;
  • hobbies是数组类型的键值对;
  • address是对象类型的键值对;
  • phoneNumbers是null类型的键值对。

JSON的解析与生成

在Android中,我们可以使用内置的JSON库来完成JSON的解析与生成。该库提供了一系列方法,用于将JSON转换成Java对象,并将Java对象转换成JSON数据。

JSON的解析

在Android中,我们可以使用JSONObject和JSONArray类来解析JSON。

解析JSONObject

以下是一个例子,演示如何解析一个JSONObject:

String jsonString = "{\"name\": \"Tom\", \"age\": 18, \"isMale\": true}";JSONObject jsonObject = new JSONObject(jsonString);String name = jsonObject.getString("name"); // 获取字符串类型的属性int age = jsonObject.getInt("age"); // 获取数字类型的属性boolean isMale = jsonObject.getBoolean("isMale"); // 获取布尔类型的属性

解析JSONArray

以下是一个例子,演示如何解析一个JSONArray:

String jsonString = "[\"Swimming\", \"Basketball\"]";JSONArray jsonArray = new JSONArray(jsonString);String hobby1 = jsonArray.getString(0); // 获取数组中的第一个项String hobby2 = jsonArray.getString(1); // 获取数组中的第二个项

JSON的生成

在Android中,我们可以使用JSONObject和JSONArray类来生成JSON。

生成JSONObject

以下是一个例子,演示如何生成一个JSONObject:

JSONObject jsonObject = new JSONObject();jsonObject.put("name", "Tom"); // 添加字符串类型的属性jsonObject.put("age", 18); // 添加数字类型的属性jsonObject.put("isMale", true); // 添加布尔类型的属性String jsonString = jsonObject.toString(); // 将JSONObject转换为字符串

生成JSONArray

以下是一个例子,演示如何生成一个JSONArray:

JSONArray jsonArray = new JSONArray();jsonArray.put("Swimming"); // 添加字符串类型的项jsonArray.put("Basketball"); // 添加字符串类型的项String jsonString = jsonArray.toString(); // 将JSONArray转换为字符串

示例说明

示例1:从URL中获取JSON并解析

以下是一个例子,演示如何从URL中获取JSON并解析:

public static String getJsonFromUrl(String url) throws IOException, JSONException {    StringBuilder resultBuilder = new StringBuilder();    InputStream inputStream = null;    try {        URL urlObj = new URL(url);        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();        connection.setRequestMethod("GET");        connection.setConnectTimeout(5000);        connection.setReadTimeout(5000);        connection.connect();        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {            inputStream = connection.getInputStream();            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);            String line;            while ((line = bufferedReader.readLine()) != null) {                resultBuilder.append(line);            }        }    } finally {        if (inputStream != null) {            inputStream.close();        }    }    return resultBuilder.toString();}public static void parseJson(String jsonString) throws JSONException {    JSONObject jsonObject = new JSONObject(jsonString);    String cityName = jsonObject.getString("name");    JSONArray jsonArray = jsonObject.getJSONArray("weather");    JSONObject weatherJsonObj = jsonArray.getJSONObject(0);    String weatherDesc = weatherJsonObj.getString("description");    System.out.println("City name: " + cityName);    System.out.println("Weather description: " + weatherDesc);}

在这个例子中,我们首先通过getJsonFromUrl方法从URL中获取JSON字符串,然后通过parseJson方法解析JSON字符串,并输出结果。假设我们获取的JSON格式如下:

{    "coord": {        "lon": 139.6917,        "lat": 35.6895    },    "weather": [        {            "id": 800,            "main": "Clear",            "description": "clear sky",            "icon": "01d"        }    ],    "base": "stations",    "main": {        "temp": 22.28,        "feels_like": 22.3,        "temp_min": 20,        "temp_max": 26.67,        "pressure": 1023,        "humidity": 37    },    "visibility": 10000,    "wind": {        "speed": 1,        "deg": 0    },    "clouds": {        "all": 0    },    "dt": 1630723776,    "sys": {        "type": 2,        "id": 2000106,        "country": "JP",        "sunrise": 1630713906,        "sunset": 1630760171    },    "timezone": 32400,    "id": 1850147,    "name": "Tokyo",    "cod": 200}

我们可以看到,这个JSON包含了城市名和天气信息。程序会输出以下内容:

City name: TokyoWeather description: clear sky

示例2:将Java对象转换为JSON

以下是一个例子,演示如何将Java对象转换为JSON字符串:

class Person {    private String name;    private int age;    private boolean isMale;    private List<String> hobbies;    private Address address;    public Person(String name, int age, boolean isMale, List<String> hobbies, Address address) {        this.name = name;        this.age = age;        this.isMale = isMale;        this.hobbies = hobbies;        this.address = address;    }    static class Address {        private String city;        private String street;        public Address(String city, String street) {            this.city = city;            this.street = street;        }    }}public static void toJson(Person person) throws JSONException {    JSONObject jsonObject = new JSONObject();    jsonObject.put("name", person.name);    jsonObject.put("age", person.age);    jsonObject.put("isMale", person.isMale);    JSONArray jsonArray = new JSONArray();    for (String hobby : person.hobbies) {        jsonArray.put(hobby);    }    jsonObject.put("hobbies", jsonArray);    JSONObject addressJsonObj = new JSONObject();    addressJsonObj.put("city", person.address.city);    addressJsonObj.put("street", person.address.street);    jsonObject.put("address", addressJsonObj);    System.out.println(jsonObject.toString());}

在这个例子中,我们创建了一个Person对象,并将该对象转换成JSON字符串。假设Person对象的实例化代码如下:

Person person = new Person(    "Tom",     18,     true,     Arrays.asList("Swimming", "Basketball"),     new Person.Address("Beijing", "Chaoyang Road"));

程序会输出以下内容:

{    "name": "Tom",    "age": 18,    "isMale": true,    "hobbies": [        "Swimming",        "Basketball"    ],    "address": {        "city": "Beijing",        "street": "Chaoyang Road"    }}

在这个例子中,我们使用了JSON对象和JSON数组来生成JSON字符串。通过put方法将对象的属性添加到JSON对象中,并将JSON数组添加到JSON对象中。

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477