android 如何使用jsonobject
时间: 2023-09-23 19:07:33 浏览: 80
1. 导入相关包
```java
import org.json.JSONException;
import org.json.JSONObject;
```
2. 创建JSONObject对象
```java
JSONObject jsonObject = new JSONObject();
```
3. 添加键值对
```java
jsonObject.put("name", "Tom");
jsonObject.put("age", 20);
```
4. 获取键值对
```java
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
```
完整示例代码:
```java
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建JSONObject对象
JSONObject jsonObject = new JSONObject();
try {
// 添加键值对
jsonObject.put("name", "Tom");
jsonObject.put("age", 20);
// 获取键值对
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
Log.d("MainActivity", "Name: " + name); // 输出:Name: Tom
Log.d("MainActivity", "Age: " + age); // 输出:Age: 20
} catch (JSONException e) {
e.printStackTrace();
}
}
}
```
阅读全文