Map轉換成JSON的方法


Map轉換成JSON的方法

1 alibaba fastjson

1.Map轉JSON

  Map<String, Object> map = new HashMap<String, Object>();
        map.put("a", "a");
        map.put("b", "123");
 
        JSONObject json = new JSONObject(map);

2.map轉string

  Map<String, Object> map = new HashMap<>();
        map.put("a", "b");
        String s = JSONObject.toJSONString(map);

3.JSON轉String

  JSONObject json = new JSONObject();
        json.put("c", "v");
        json.put("z", "123n);
 
        json.toJSONString();

4.JSON轉Map

JSONObject json = new JSONObject();
        json.put("ccc", "321");
        json.put("bbb", "123");
 
        Map<String, Object> map = (Map<String, Object>)json;

5.String轉JSON

 String str = "{\"username\":\"dsad\",\"qwewqe\":\"123\"}";
JSONObject json = JSONObject.parseObject(str);

2 google

maven坐標

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>

Map轉換成JSON

Map<String,String> map = new HashMap<String,String>(); 
map.put("a","aaa"); 
map.put("b","bbb"); 
map.put("c","ccc"); 
String json=JSON.toJSONString(map); 
System.out.println(json);//輸出{"a":"aaa","b":"bbb","c":"ccc"}

JSON轉換成Map

Map map1 = JSON.parseObject(json);
System.out.println(map1.get("a"));
for (Object mapData : map.entrySet()) {
Map.Entry<String,String> entry = (Map.Entry<String,String>)mapData;
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
/*輸出
b--->bbb
c--->ccc
a--->aaa
*/

map中含有對象Map -> JSON

//Map -> JSON
Map<String,Bar> map = new HashMap<String, Bar>(); 
map.put("a",new Bar()); 
map.put("b",new Bar()); 
map.put("c",new Bar()); 
String json = JSON.toJSONString(map,true); 
System.out.println(json); 
/*
輸出{
	"a":{
		"barAge":383687382,
		"barDate":1494945882018,
		"barName":"name_1689176802"
	},
	"b":{
		"barAge":-100528778,
		"barDate":1494945882018,
		"barName":"name_-878176366"
	},
	"c":{
		"barAge":-344075192,
		"barDate":1494945882018,
		"barName":"name_-1710740534"
	}
}
*/

JSON -> Map

Map<String,Bar> map1 = (Map<String,Bar>)JSON.parse(json); 
for (String key : map1.keySet()) { 
System.out.println(key+":"+map1.get(key)); 
} 
/*輸出
b:{"barAge":-100528778,"barDate":1494945882018,"barName":"name_-878176366"}
c:{"barAge":-344075192,"barDate":1494945882018,"barName":"name_-1710740534"}
a:{"barAge":383687382,"barDate":1494945882018,"barName":"name_1689176802"}
*/

MAP的ASCII排序

StringBuilder sb = new StringBuilder();
	List<String> keys = new ArrayList<String>(map.keySet());
	Collections.sort(keys);//排序。
	for(String k : keys){
		String v = params.get(k);
		if(StringUtils.isNotEmpty(v)){
			sb.append(v);
		}
	}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM