json数组和json字符串转换成map解析

时间:2024-08-03 12:06:20

package demo;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ResolveJson {
 public static void main(String[] args) {
  
  //JSONArray型装换成map遍历
  String jsonStr = "[{'0':'06:00-23:00;1\\u5206\\u949f;80\\u6b65\\/\\u5206-90\\u6b65\\/\\u5206','1':'06:00-23:00;1\\u5206\\u949f;80\\u6b65\\/\\u5206-90\\u6b65\\/\\u5206','2':'06:00-23:00;20\\u5206\\u949f;80\\u6b65\\/\\u5206-90\\u6b65\\/\\u5206'}]";
  JSONArray array = JSONArray.fromObject(jsonStr);
  System.out.println(array);
  List<Map<String, Object>> mapListJson = (List<Map<String, Object>>) array;
  for (int i = 0; i < mapListJson.size(); i++) {
   Map<String, Object> obj = mapListJson.get(i);
   for (Entry<String, Object> entry : obj.entrySet()) {
    String strkey1 = entry.getKey();
    Object strval1 = entry.getValue();
    System.out.println("KEY:" + strkey1 + "  -->  Value:" + strval1 +"\n");
   }
 }

// JSONObject型装换成map遍历
  String jsonObjectData = "{\"0\":\"06:00-23:00;1\\u5206\\u949f;80\\u6b65\\/\\u5206-90\\u6b65\\/\\u5206\",\"1\":\"06:00-23:00;1\\u5206\\u949f;80\\u6b65\\/\\u5206-90\\u6b65\\/\\u5206\",\"2\":\"06:00-23:00;20\\u5206\\u949f;80\\u6b65\\/\\u5206-90\\u6b65\\/\u5206\"}";
  JSONObject jsonObject = JSONObject.fromObject(jsonObjectData);
  Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
  for (Entry<String, Object> entry : mapJson.entrySet()) {
   String strkey1 = entry.getKey();
   Object strval1 = entry.getValue();
   System.out.println("KEY:" + entry.getKey() + "  -->  Value:" + entry.getValue() + "\n");
  }
 }
}