手机怎么写JSON格式:从基础到实践的全面指南
JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,因其简洁、易读、易于机器解析和生成,已成为移动端开发中数据存储、网络传输、配置管理的主流选择,无论是Android还是iOS开发,手机端JSON的“写法”(包括生成、写入、解析等操作)都是开发者的必备技能,本文将从JSON的基础概念出发,结合Android和iOS两大平台的实际场景,详细讲解手机端JSON的完整操作流程。
先搞懂:什么是JSON?为什么手机端需要它?
JSON本质上是一种数据结构,由“键值对”(Key-Value Pair)组成,格式类似JavaScript对象,但更通用,它支持两种核心结构:
- 对象(Object):用 包裹,由多个键值对组成,键需用双引号括起,值可以是字符串、数字、布尔值、数组、嵌套对象等,
{"name":"张三","age":25,"isStudent":false} - 数组(Array):用
[]包裹,元素可以是任意类型(包括对象),[{"name":"李四","age":30},{"name":"王五","age":28}]
为什么手机端需要JSON?
- 网络传输:手机APP与服务器交互时,JSON是HTTP请求/响应的常见数据格式(如API接口返回的数据)。
- 本地存储:Android的
SharedPreferences、iOS的UserDefaults适合存储简单键值对,而复杂数据(如用户信息、配置列表)更适合用JSON存储到文件或数据库。 - 跨平台兼容:JSON是语言无关的,Android(Java/Kotlin)、iOS(Swift/OC)都能轻松解析和生成,方便数据在不同平台间共享。
手机端JSON的“写法”:从生成到写入的完整流程
手机端处理JSON的核心操作分为三步:生成JSON数据(将内存中的对象/数据转换为JSON字符串)、写入JSON数据(将JSON字符串保存到本地文件、数据库或发送到服务器)、解析JSON数据(读取本地/网络JSON并还原为对象),本文重点讲解“生成”和“写入”步骤,解析作为补充。
(一)Android端:Kotlin/Java生成与写入JSON
Android开发中,生成JSON的方式主要有两种:手动拼接字符串(不推荐,易出错)或使用第三方库(推荐,高效且安全),常用库有org.json(Android原生)、Gson(Google)、Moshi(Square)。
使用org.json库(原生支持,无需额外依赖)
Android系统已内置org.json库,可直接使用。
步骤1:添加依赖(无需额外操作,已内置)
若使用Kotlin,需在build.gradle中添加implementation("org.json:json:20231013")(部分旧版本可能无需添加)。
步骤2:生成JSON字符串
以Kotlin为例,通过JSONObject和JSONArray构建JSON数据:
import org.json.JSONObject
import org.json.JSONArray
fun createJson(): String {
// 创建JSON对象(对应{})
val user = JSONObject().apply {
put("name", "张三")
put("age", 25)
put("isStudent", false)
// 嵌套JSON对象
put("address", JSONObject().apply {
put("city", "北京")
put("district", "朝阳区")
})
}
// 创建JSON数组(对应[])
val hobbies = JSONArray().apply {
put("阅读")
put("游泳")
put("编程")
}
// 将数组作为对象的值
user.put("hobbies", hobbies)
return user.toString() // 转换为JSON字符串
}
调用createJson()会返回:
{"name":"张三","age":25,"isStudent":false,"address":{"city":"北京","district":"朝阳区"},"hobbies":["阅读","游泳","编程"]}
步骤3:写入JSON到本地文件
将生成的JSON字符串保存到手机存储(需申请权限):
import android.content.Context
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
fun saveJsonToFile(context: Context, json: String, fileName: String) {
try {
// 获取应用私有存储目录(无需存储权限)
val file = File(context.filesDir, fileName)
FileOutputStream(file).use { fos ->
fos.write(json.toByteArray())
}
// 或使用ContextCompat.openFileOutput(更简单)
// context.openFileOutput(fileName, Context.MODE_PRIVATE).use { fos ->
// fos.write(json.toByteArray())
// }
} catch (e: IOException) {
e.printStackTrace()
}
}
调用saveJsonToFile(context, createJson(), "user.json")后,文件会保存在/data/data/包名/files/user.json。
使用Gson库(推荐,支持对象自动转JSON)
Gson是Google开发的库,能直接将Kotlin/Java对象转换为JSON字符串,无需手动拼接,适合处理复杂数据。
步骤1:添加依赖
在build.gradle中添加:
implementation("com.google.code.gson:gson:2.10.1")
步骤2:定义数据类
用Kotlin数据类映射JSON结构:
data class User(
val name: String,
val age: Int,
val isStudent: Boolean,
val address: Address,
val hobbies: List<String>
)
data class Address(
val city: String,
val district: String
)
步骤3:生成JSON字符串
import com.google.gson.Gson
fun generateJsonWithGson(): String {
val address = Address(city = "上海", district = "浦东新区")
val user = User(
name = "李四",
age = 30,
isStudent = false,
address = address,
hobbies = listOf("跑步", "摄影", "旅游")
)
return Gson().toJson(user) // 直接转换为JSON字符串
}
输出结果与org.json一致,但代码更简洁。
步骤4:写入JSON到SharedPreferences(适合小数据)
SharedPreferences本质是键值对存储,但可通过Gson存取复杂数据:
fun saveUserToSharedPreferences(context: Context, user: User) {
val json = Gson().toJson(user)
context.getSharedPreferences("user_data", Context.MODE_PRIVATE).edit().apply {
putString("user_json", json)
apply() // 异步提交
}
}
(二)iOS端:Swift生成与写入JSON
iOS开发中,生成JSON主要使用JSONSerialization(系统原生)或第三方库Codable(推荐,类型安全)。Codable是Swift 4+引入的协议,能自动实现JSON与对象的转换,代码更优雅。
使用Codable协议(推荐,类型安全)
步骤1:定义模型(遵循Codable)
import Foundation
struct User: Codable {
let name: String
let age: Int
let isStudent: Bool
let address: Address
let hobbies: [String]
}
struct Address: Codable {
let city: String
let district: String
}
步骤2:生成JSON字符串
func generateJsonWithCodable() -> String? {
let address = Address(city: "广州", district: "天河区")
let user = User(
name: "王五",
age: 28,
isStudent: true,
address: address,
hobbies: ["画画", "音乐", "健身"]
)
// 将对象转换为JSON数据(Data)
guard let jsonData = try? JSONEncoder().encode(user) else {
return nil
}
// 将JSON数据转换为字符串
return String(data: jsonData, encoding: .utf8)
}
调用generateJsonWithCodable()会返回JSON字符串。
步骤3:写入JSON到本地文件
import Foundation
func saveJsonToFile(jsonString: String, fileName: String) {
guard let jsonData = jsonString.data(using: .utf8) else { return }
// 获取文档目录路径
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsDirectory.appendingPathComponent(fileName)
do {
try jsonData.write(to: fileURL, options: .atomic)
print("文件保存成功:\(fileURL.path)")
} catch {
print("保存失败:\(error.localizedDescription)")
}
}
调用saveJsonToFile(jsonString: generateJsonWithCodable() ?? "", fileName: "user.json")后,文件会保存在`/Documents/user



还没有评论,来说两句吧...