json对象转map,map转json
程序员文章站
2024-02-15 19:25:59
...
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<String, String>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
System.out.println(map);
String json = JSON.toJSONString(map);//map转String
System.out.println(json);
String jsonString = JSONObject.toJSONString(map);
System.out.println(jsonString);
JSONObject jsonObject = JSON.parseObject(json);
System.out.println(jsonObject);
/**
* student对象转换成json字符串 解析成map(对象)
* map对象转换成json字符串 解析成student(对象)
*/
Student student=new Student();
Date date=new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
sdf.format(date);
student.setId(1);
student.setStudentName("李四");
student.setScore("15");
student.setBrithday(sdf.format(date));
String string = JSON.toJSONString(student);
System.out.println(string);
Map map1 = JSON.parseObject(string, Map.class);
System.out.println(map1);
/**
* map对象转json字符串 方法一:json.toJSONSting();
*/
String mapjson = JSON.toJSONString(map1);
System.out.println(mapjson);
/**
* map对象转json字符串 方法二:JSONObject.toJONString();
*/
String jsonString1 = JSONObject.toJSONString(map1);
System.out.println(jsonString1);
/**
* map对象转json字符串 方法三:对象.toString();
*/
JSONObject jsonObject1 = new JSONObject(map1);
String toString = jsonObject1.toString();
System.out.println(toString);
/**
* json字符串解析成student对象 JSON.parseObject(jsonString,Class)
*/
Student student1 = JSON.parseObject(mapjson, Student.class);
System.out.println(student1);
}
上一篇: Yaf入门