共计 2599 个字符,预计需要花费 7 分钟才能阅读完成。
在 Android 开发中,处理 JSON 字符串和将字符串转换为 JSON 对象是一个常见的任务。以下是如何在 Android 中实现这一功能的步骤:
### 1. 将字符串转换为 JSON 对象
要将一个 JSON 格式的字符串转换为 JSON 对象,你可以使用如 `org.json` 库中的 `JSONObject` 类。
** 添加依赖 **(如果使用 Gradle):
“`gradle
dependencies {
implementation ‘org.json:json:20210307’
}
“`
** 代码示例 **:
“`java
import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
String jsonString = “{“name”:”John”, “age”:30, “city”:”New York”}”;
try {
// 将字符串转换为 JSONObject
JSONObject jsonObject = new JSONObject(jsonString);
// 从 JSONObject 中获取数据
String name = jsonObject.getString(“name”);
int age = jsonObject.getInt(“age”);
String city = jsonObject.getString(“city”);
// 打印获取到的数据
System.out.println(“Name: ” + name);
System.out.println(“Age: ” + age);
System.out.println(“City: ” + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
“`
### 2. 创建 JSON 字符串
如果你需要从基本数据类型创建一个 JSON 字符串,你可以使用 `JSONObject` 来构建它。
** 代码示例 **:
“`java
import org.json.JSONObject;
public class JsonCreationExample {
public static void main(String[] args) {
try {
// 创建一个新的 JSONObject
JSONObject jsonObject = new JSONObject();
// 添加数据
jsonObject.put(“name”, “John”);
jsonObject.put(“age”, 30);
jsonObject.put(“city”, “New York”);
// 将 JSONObject 转换为 JSON 字符串
String jsonString = jsonObject.toString();
// 打印 JSON 字符串
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
“`
### 3. 使用 Gson 库转换对象和 JSON
如果你有一个 Java 对象,并希望将其转换为 JSON 字符串,或者相反,你可以使用 Google 的 Gson 库。
** 添加依赖 **(如果使用 Gradle):
“`gradle
dependencies {
implementation ‘com.google.code.gson:gson:2.8.6’
}
“`
** 将对象转换为 JSON 字符串 **:
“`java
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
User user = new User(“John”, 30, “New York”);
// 创建 Gson 实例
Gson gson = new Gson();
// 将用户对象转换为 JSON 字符串
String json = gson.toJson(user);
System.out.println(json);
}
static class User {
String name;
int age;
String city;
User(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}
}
“`
** 将 JSON 字符串转换为对象 **:
“`java
import com.google.gson.Gson;
public class GsonParseExample {
public static void main(String[] args) {
String json = “{“name”:”John”, “age”:30, “city”:”New York”}”;
// 创建 Gson 实例
Gson gson = new Gson();
// 将 JSON 字符串转换为 User 对象
User user = gson.fromJson(json, User.class);
System.out.println(“Name: ” + user.name);
System.out.println(“Age: ” + user.age);
System.out.println(“City: ” + user.city);
}
static class User {
String name;
int age;
String city;
}
}
“`
使用这些方法,你可以轻松地在 Android 应用中处理 JSON 数据。
原文地址: json 字符串,string 转 json