json轉list,map,list;list,map,list轉json
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);
}
}
}