package com.example.demo.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* JSON数据的工具类,可以封装JSOn对象、JSON数组字符串
*/
public class JsonUtil {
/**
* 封装单个的JSON数据(有Key)
*/
public static String createJSONhaveKey() throws JSONException {
//格式:{"Person":{"name":"张三","age":20,"sex":"男"}}
JSONObject jsonObject=new JSONObject();
JSONObject jsonstring=new JSONObject();
//添加数据
jsonObject.put("name","张三");
jsonObject.put("age",20);
jsonObject.put("sex","男");
//添加到字符串对象中并设置key
jsonstring.put("Person",jsonObject);
return jsonstring.toString();
}
/**
* 解析单个json数据(有key)
*/
public static void analysisJSONhaveKey(String jsonObjectstring) throws JSONException {
JSONObject jsonObject=new JSONObject(jsonObjectstring);
JSONObject json=jsonObject.getJSONObject("Person");//通过Key获取值
String name=json.getString("name");
String sex=json.getString("sex");
int age=json.getInt("age");
System.out.println("姓名:"
Java对JSON数据的封装与解析
最新推荐文章于 2023-12-05 15:39:06 发布