用java在androidstudio写一个josn的api程序
时间: 2023-05-23 20:07:01 浏览: 125
A:下面是一个简单的Java代码示例,用于在Android Studio中编写JSON API程序:
1. 首先,要在build.gradle文件中添加以下依赖项,以使用JSON库:
```
dependencies {
implementation 'org.json:json:20190722'
}
```
2. 然后,创建一个名为JsonApi的Java类并添加以下代码:
```
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonApi {
public static void main(String[] args) {
String jsonData = "{ \"name\":\"John\", \"age\":30, \"city\":\"New York\" }";
try {
JSONObject jsonObject = new JSONObject(jsonData);
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 (JSONException e) {
e.printStackTrace();
}
String jsonArrayData = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":40, \"city\":\"Los Angeles\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonArrayData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
System.out.println("--- Person " + (i+1) + " ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
```
3. 运行该程序,将输出以下内容:
```
Name: John
Age: 30
City: New York
--- Person 1 ---
Name: John
Age: 30
City: New York
--- Person 2 ---
Name: Jane
Age: 40
City: Los Angeles
```
这个示例程序演示了如何使用JSON库解析JSON数据。您可以将其作为起点并根据自己的需求对其进行修改和扩展。
阅读全文