Map與JSON中的各種互轉
阿新 • • 發佈:2020-07-24
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestJSON {
public static void main(String[] args) {
/*
最常見的key對應一個String的。例如:("card_id": "233bcbf407e87789b8e471f251774f95")
*/
Map<String, Object> map = new HashMap<>();
map.put("card_id", "233bcbf407e87789b8e471f251774f95");
/*
key 對應 Object的。
例如:"time_range": {
"betin_time": "2020-05-20T13:29:35.120+08:00","end_time": "2020-05-21T13:29:35.120+08:00"
}
*/
Map<String, Object> map1 = new HashMap<>();
map1.put("betin_time", "2020-05-20T13:29:35.120+08:00");
map1.put("end_time", "2020-05-21T13:29:35.120+08:00");
// map轉StringString object = JSON.toJSONString(map1);
map.put("time_range", object);
/*
key 對應 array的。
"objectives" : [
{
"unit" : "次",
"name" : "一週購買三次商品",
"count" : 1,
"description" : "特價商品",
"objective_id" : "1234"
},
{
"unit" : "次",
"name" : "一週購買六次商品",
"count" : 2,
"description" : "優惠商品",
"objective_id" : "5678"
}
]
*/
Map<String, Object> map2 = new HashMap<>();
map2.put("unit", "次");
map2.put("name", "一週購買三次商品");
map2.put("count", 1);
map2.put("description", "特價商品");
map2.put("objective_id", "1234");
String s2 = JSON.toJSONString(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("unit", "次");
map3.put("name", "一週購買六次商品");
map3.put("count", 2);
map3.put("description", "優惠商品");
map3.put("objective_id", "5678");
String s3 = JSON.toJSONString(map3);
List array = new ArrayList<>();
array.add(s2);
array.add(s3);
map.put("objectives", array);
// 整個map轉String
String mmm = JSON.toJSONString(map);
System.out.println("map = " + mmm);
// String轉JSONObject
JSONObject jsonObject = JSON.parseObject(mmm);
System.out.println("time_range = " + jsonObject.get("time_range"));
JSONObject json = JSON.parseObject(jsonObject.get("time_range").toString());
System.out.println("betin_time = " + json.get("betin_time"));
System.out.println("end_time = " + json.get("end_time"));
// String轉JSONArray
JSONArray objectives = JSON.parseArray(jsonObject.get("objectives").toString());
for (int i = 0; i < objectives.size(); i++) {
System.out.println("objectives中的第" + i + "個unit = " + JSON.parseObject(objectives.get(i).toString()).get("unit"));
System.out.println("objectives中的第" + i + "個name = " + JSON.parseObject(objectives.get(i).toString()).get("name"));
System.out.println("objectives中的第" + i + "個count = " + JSON.parseObject(objectives.get(i).toString()).get("count"));
System.out.println("objectives中的第" + i + "個description = " + JSON.parseObject(objectives.get(i).toString()).get("description"));
System.out.println("objectives中的第" + i + "個objective_id = " + JSON.parseObject(objectives.get(i).toString()).get("objective_id"));
System.out.println("===========================商品分割線=================================");
}
}
}