JAVA高级教程-Json,Map,String之间的互转(11)

目录

    • 1、Map转JSON
    • 2、**Map**转String
    • 3、JSON转String
    • 4、JSON转Map
    • 5、String转JSON
    • 6、将Json格式的字符串转换为对象
    • 7、将map转换为对象
  • 第二种 google
    • 总结

1、Map转JSON

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

2、Map转String

  Map 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 map = (Map)json;

5、String转JSON

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

6、将Json格式的字符串转换为对象

import lombok.Data;@Datapublic class AlertRule {    private String relation;    private  UpperLower diffAbs;    private  UpperLower diffPercent;}
@Datapublic class UpperLower {    private BigDecimal upper;    private  BigDecimal lower;}
        AlertRule alertRule= JSON.parseObject("{\"diffAbs\":{\"upper\":2000,\"lower\":23000},\"diffPercent\":{\"upper\":2000,\"lower\":23000},\"relation\":\"OR\"}",AlertRule.class);        System.out.println(alertRule.getDiffAbs());

7、将map转换为对象

public class Test01 {    private static class Obj1 {        private String School;        private List studen;        public List getStuden() {            return studen;        }        public void setStuden(List studen) {            this.studen = studen;        }        public String getSchool() {            return School;        }        public void setSchool(String school) {            School = school;        }    }    public static void main(String[] args) {        Map map = new HashMap();        map.put("studens","{\"city\":{\"School\":\"san\",\"studen\":[1,2,3]}}");        Map student = JSON.parseObject(map.get("studens"), new TypeReference<Map>(){});        System.out.println(student);        Set<Map.Entry> entries=student.entrySet();        for(Map.Entry aa:entries){            System.out.println(aa);            Obj1 value=aa.getValue();            String school=value.getSchool();            System.out.println(school);            List studet=value.getStuden();            System.out.println(studet);        }    }}

第二种 google

maven坐标



    com.google.code.gson
    gson
    2.3.1

//Map转换成JSON

Map map = new HashMap(); 
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 entry = (Map.Entry)mapData;
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
/*输出
b--->bbb
c--->ccc
a--->aaa
*/

map中含有对象Map -> JSON

//Map -> JSON
Map map = new HashMap(); 
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 map1 = (Map)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 keys = new ArrayList(map.keySet());
	Collections.sort(keys);//排序。
	for(String k : keys){
		String v = params.get(k);
		if(StringUtils.isNotEmpty(v)){
			sb.append(v);
		}
	}
	//return MD5.toMD5(sb+key, "UTF-8");这个就不用看了~~~

总结

    public static void main(String[] args) {
        JSONObject alertRule= JSON.parseObject("{\"diffAbs\":{\"upper\":2000,\"lower\":23000},\"diffPercent\":{\"upper\":2000,\"lower\":23000},\"relation\":\"OR\"}");
        //json--string
        String a=JSONObject.toJSONString(alertRule);
        
        //string---json
        JSONObject b=JSONObject.parseObject(a);
        
        //json--map
        Map json_map=(Map)b;
        
        //map--string
        String c=JSONObject.toJSONString(json_map);

        //map--json
        JSONObject d=new JSONObject(json_map);

        //string--map
        Map e=JSONObject.parseObject(c,Map.class);

        //map-对象

    }
//1.Map转JSON
        Map map1 = new HashMap();
        map1.put("a", "a");
        map1.put("b", "123");
        JSONObject json = new JSONObject(map1);
        System.out.println("map"+map1);
        System.out.println("map->json"+json);

        //5.String转JSON
        String str = "{\n" +
                "    \"username\":\"dsad\",\n" +
                "    \"qwewqe\":\"123\"\n" +
                "}";
        JSONObject json3 = JSONObject.parseObject(str);
        System.out.println("string-json"+json3);


        //2.map转json string
        Map map2 = new HashMap();
        map2.put("a", "b");
        String s = JSONObject.toJSONString(map2);

        System.out.println("map"+map2);
        System.out.println("map-string1"+JSON.toJSONString(map2));
        System.out.println("map-string2"+s);

        //3.JSON转String
        JSONObject json1 = new JSONObject();
        json1.put("c", "v");
        json1.put("z", "123n");
        String ss=json.toJSONString(json1);
        System.out.println("json-string"+ss);

        //4.JSON转Map
        JSONObject json2 = new JSONObject();
        json2.put("ccc", "321");
        json2.put("bbb", "123");

        Map maps = (Map)json2;
        System.out.println("json->map"+maps);
        System.out.println(maps.get("ccc"));


        // string-map
        String str1 = "{\n" +
                "    \"username\":\"dsad\",\n" +
                "    \"qwewqe\":\"123\"\n" +
                "}";
        Map newmap = JSON.parseObject(s, Map.class);
        System.out.println("str->map"+newmap);
        
        @Data
        class User {
            String name;
            int age;
            BigDecimal salary;
        }

        //对象和map之间的转换
        User user = new User();
        user.setName("校长");
        user.setAge(3);
        user.setSalary(new BigDecimal("123456789.0123"));
        /*对象转map*/
        String jsonString1 = JSON.toJSONString(user);
        Map mapmap = JSON.parseObject(jsonString1, Map.class);
        System.out.println("map = " + mapmap);// map = {name=校长, salary=123456789.0123, age=3}

        String jsonString = JSON.toJSONString(mapmap);
        User user1 = JSON.parseObject(jsonString, User.class);//json转对象
        System.out.println("user1 = " + user1); //user1 = User{name='校长', age=3, salary=123456789.0123}

转载自:https://blog.csdn.net/web18296061989/article/details/123657550
如还看不懂,可参考案例:https://blog.csdn.net/u014212540/article/details/127687138

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/f1374acc97.html