import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonChange {
public static void main(String[] args) {
// list转object对象
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
JSONArray jsonArray = JSONArray.fromObject(list);
for (int i = 0; i < jsonArray.size(); i++) {
System.out.print(jsonArray.get(i));
}
System.out.println();
// json对象转list
List<String> ts = (List<String>) JSONArray.toList(jsonArray);
System.out.println(ts.get(0));
// Map转json对象
Map<String, String> num_map = new HashMap();
System.out.println("迭代器KeySet遍历:");
Iterator iterator = num_map.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println("key=" + num_map.get(key) + ",");
}
num_map.put("1", "asd");
num_map.put("2", "qwe");
num_map.put("3", "rtt");
JSONArray jsonArray2 = JSONArray.fromObject(num_map);
for (int i = 1; i <= num_map.size(); i++) {
String string = "" + i + "";
System.out.print(num_map.get(string));
}
System.out.println();
// json对象转字符串
System.out.println(jsonArray2.toString());
// json对象转Map
// //所有的jsonArray先转成jsonObeject,然后再转成map
JSONObject myjObject = null;
for (int i = 0; i < jsonArray2.size(); i++) {
// 获取每一个JsonObject对象
myjObject = jsonArray2.getJSONObject(i);
}
Map<String, Object> changemap = new HashMap<>();
for (Object k : myjObject.keySet()) {
Object v = myjObject.get(k);
changemap.put(k.toString(), v);
}
// List<Map>转json对象
List<Map<String, String>> listmap = new ArrayList<>();
listmap.add(num_map);
JSONArray jsonArray3 = JSONArray.fromObject(listmap);
for (int i = 0; i < listmap.size(); i++) {
String string = "" + i + "";
System.out.print(listmap.get(i));
}
System.out.println();
// json对象转List<Map>
System.out.println("json对象转List<Map>");
List<Map> jList = (List<Map>) JSONArray.toCollection(jsonArray3, Map.class);
for (Map map : jList) {
System.out.println(map);
}
}
}