Map与JSON中的各种互转

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转String
String 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("===========================商品分割线=================================");
}
}
}

Map与JSON中的各种互转

上一篇:HTML标签区别


下一篇:phpMyAdmin配置文件中的密文(blowfish_secret)太短