1. JSONObject,JSON对象中有一个键对应一个值,大括号形式包含,{key:value}
2. json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的
Json对象中添加的是键值对,JSONArray中添加的是Json对象
JSON对象创建方法:
//----------------JsonObject创建的方法-----------------------------------------------------------
//创建JsonObject第一种方法
JSONObject jsonObject = new JSONObject();
jsonObject.put("UserName", "kobi");
jsonObject.put("age", "34");
jsonObject.put("workIn", "ALI");//此处的"ALI"也可以替换为一个json{"sex":"男","station":"徐州","hoobey":"coding"}
// System.out.println("jsonObject1:" + jsonObject);//jsonObject1:{"UserName":"kobi","workIn":"ALI","age":"34"}
Iterator iterator = jsonObject.keys();//用Iterator迭代器遍历取值,建议用反射机制解析到封装好的对象中
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jsonObject.getString(key);
System.out.println(value);//输出值 kobi ALI 34
//创建JsonObject第二种方法
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("UserName", "ZHULI");
hashMap.put("age", "30");
hashMap.put("workIn", "ALI");
// System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));//jsonObject2:{"UserName":"ZHULI","workIn":"ALI","age":"30"}
//----------------JSONArray创建的方法-----------------------------------------------------------
//一:遍历JsonArray
String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]"; // 一个未转化的字符串
JSONArray json = JSONArray.fromObject(str); // 首先把字符串转成 JSONArray 对象
if (json.length() > 0) {
for (int i = 0; i < json.length(); i++) {
JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象
// System.out.println(job);//{"name":"a","value":"aa"} {"name":"b","value":"bb"} {"name":"c","value":"cc"}.....
// System.out.println(job.get("name")); // a b c d
//创建JsonArray方法2
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("kobi");
arrayList.add("34");
arrayList.add("ALI");
//System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));//jsonArray2:["kobi","34","ALI"]
@Test
public void test0105() {
取出name4值过程步骤: 1.将以上字符串转成JSONArray对象 2.取出对象的第一项,JSONObject 3.取出name1的值JSONObject
4.然后取出name2的值JSONObject对象 5.取出name4的值value2
/* 记住":"前是键,符号后是值 大括号成对找 一层层拨开就清楚了*/
String str = "[{name1:{name2:{name3:'value1',name4:'value2'}}},{}]";
JSONArray jsonArray = JSONArray.fromObject(str);// 将结果转成JSONArray对象的形式
JSONObject getJsonObj = jsonArray.getJSONObject(0);//获取json数组中的第一项
JSONObject json = getJsonObj.getJSONObject("name1").getJSONObject("name2");//{"name4":"value2","name3":"value1"}
Object value = json.get("name4");
System.out.println(value);//value2
@Test
public void test01051() {
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
json.put("key", "value");//JSONObject对象中添加键值对
jsonArray.put(json);//将JSONObject对象添加到Json数组中
System.out.println(json);
System.out.println(jsonArray);
相互转化如下:
将javaBean转换成Map:
public static Map<String, String> BeantoMap(Object javaBean) {
Map<String, String> result = new HashMap<String, String>();
Method[] methods = javaBean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("get")) {
//method.getName().startsWith("get")表示从找到get开头的方法
String field = method.getName();//getName getPassword
field = field.substring(field.indexOf("get") + 3);//Name Password
field = field.toLowerCase().charAt(0) + field.substring(1);//name password
Object value = method.invoke(javaBean, (Object[]) null);
result.put(field, null == value ? "" : value.toString());
}
}
catch (Exception e) {
}
}
return result;
}
将json对象转换成Map:
@SuppressWarnings("unchecked")
public static Map<String, String> JsontoMap(JSONObject jsonObject) {
Map<String, String> result = new HashMap<String, String>();
Iterator<String> iterator = jsonObject.keys();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = iterator.next();
value = jsonObject.getString(key);
result.put(key, value);
return result;
将javaBean转换成JSONObject:
public static JSONObject toJSON(Object bean) {
return new JSONObject(BeantoMap(bean));
将map转换成Javabean:
public static Object toJavaBean(Object javabean, Map<String, String> data) {
Method[] methods = javabean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("set")) {
String field = method.getName(); //setName setPassword
field = field.substring(field.indexOf("set") + 3);//Name Password
field = field.toLowerCase().charAt(0) + field.substring(1);//name password
method.invoke(javabean, new Object[]
data.get(field)
} catch (Exception e) {
e.printStackTrace();
return javabean;
方法调用如下:
/*javaBean转换成Map*/
@Test
public void test1(){
Map<String, String> map = BeanConverter.BeantoMap(new Stu("hoobey","123"));
// Map<String, String> map = BeanConverter.toMap(new Stu("hoobey", "213"));
// Set<Map.Entry<String, String>> entry = map.entrySet(); //Set集合中存储的是Map.Entry<String, String> entry
//推荐使用这种map遍历 尤其是容量大的时候 map.entrySet()返回此映射中包含的映射关系的 Set视图
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println("key="+entry.getKey()+",value="+entry.getValue());
/* * 将json对象转换成Map*/
@Test
public void test2(){
JSONObject json =new JSONObject();
json.put("hoobey","123"); //{"hoobey":"123"}
Map<String, String> toMap = BeanConverter.JsontoMap(json);
for(Map.Entry<String, String> entry : toMap.entrySet()){
System.out.println("key="+entry.getKey()+",value="+entry.getValue());
/*将javaBean转换成JSONObject*/
@Test
public void test3(){
JSONObject toJSON = BeanConverter.toJSON(new Stu("hoobey", "123"));
System.out.println(toJSON);//{"password":"123","name":"hoobey"}
/*将map转换成Javabean map中存放的键值一定和bean相对应*/
@Test
public void test4(){
Map<String, String> map = new HashMap<String, String>();
map.put("name","hoobey");
map.put("password","123");
Object o = BeanConverter.toJavaBean(new Stu(), map);
System.out.println(o);//Stu{name='hoobey', password='123'}
转载自:https://www.cnblogs.com/hoobey/p/8213670.html