思路是JavaBean、Map、XML都可以用工具类很简单的转换为Json,进而实现互相转换
1.Map、XML与Json互转
mvn依赖 <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20171018</version> </dependency>
entity public class Student { private String name; private String sex; private int age; }
import org.json.JSONObject; import org.json.XML; import java.util.HashMap; import java.util.Map; public class JsonUtil { public static String JsonToXml(String json){ JSONObject jsonObject = new JSONObject(json); return XML.toString(jsonObject) ; } public static String XmlToJson(String xml){ JSONObject jsonObject = XML.toJSONObject(xml); return jsonObject.toString(); } public static String MapToJson(Map map){ JSONObject jsonObject = new JSONObject(map); return jsonObject.toString(); } public static Map JsonToMap(String json){ JSONObject jsonObject = new JSONObject(json); return jsonObject.toMap(); } public static String BeanToJson(Object object){ JSONObject jsonObject = new JSONObject(object); return jsonObject.toString(); } public static void main(String[] args) { Map map = new HashMap(); map.put("name","小明"); map.put("sex","男"); map.put("age",10); String json = MapToJson(map); System.out.println(json); Map map1 = JsonToMap(json); System.out.println(map1); String xml = JsonToXml(json); System.out.println(xml); String json1 = XmlToJson(xml); System.out.println(json1); // bean to json Student student = new Student("小红","女",20); String json2 = BeanToJson(student); System.out.println(json2); } }
执行结果
{"name":"小明","age":10,"sex":"男"} {sex=男, name=小明, age=10} <sex>男</sex><name>小明</name><age>10</age> {"sex":"男","name":"小明","age":10} {"sex":"女","name":"小红","age":20}
2.JavaBean与Json互转
mvn依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.9</version> </dependency>
import com.alibaba.fastjson.JSON; public class JsonUtil2 { public static String BeanToJson(Object object){ String json = JSON.toJSONString(object); return json; } public static <T>T JsonToBean(String json,Class<T> clazz){ return JSON.parseObject(json,clazz); } public static void main(String[] args) { Student student = new Student("小张","男",28); String json = BeanToJson(student); System.out.println(json); Student student1 = JsonToBean(json,Student.class); System.out.println(student1); } }
执行结果
{"age":28,"name":"小张","sex":"男"} Student{name=‘小张‘, sex=‘男‘, age=28}
3.常用的json工具类除了上面两个以外还有jackson
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency>
原文地址:https://www.cnblogs.com/scorates/p/10600946.html
时间: 2024-10-11 15:53:00