1、字符串转map
String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
//第一种方式
Map maps = (Map)JSON.parse(str);
System.out.println("这个是用JSON类来解析JSON字符串!!!");
2、jsonString转jsonObject
String jsonStr = "{\"school\":\"商职\",\"sex\":\"男\",\"name\":\"wjw\",\"age\":22}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getInteger("age"));
3、jsonString转xml
/**
* json字符串转换成xml格式字符串
* @return
*/
public static String json2Xml(){
String json = "{\"business\":{\"body\":{\"fpdm\":\"发票代码\",\"fplxdm\":\"发票类型代码\",\"kpzdbs\":\"开票终端标识\",\"dyfs\":\"打印方式\",\"dylx\":\"打印类型\",\"printername\":\"打印机名称\",\"fphm\":\"发票号码\"}}}";
JSONObject jsonObject = new JSONObject(json);
String xml = XML.toString(jsonObject);
return xml;
}
4、jsonString转Java对象
JSONObject jsonobject = JSONObject.fromObject(jsonStr);
User user= (User)JSONObject.toBean(object,User.class);
5、xml转map(单层)
/**
* XML格式字符串转换为Map
*
* @param xml XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String xml) {
try {
Map<String, String> data = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
stream.close();
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
6、(多层)xml格式字符串转换为map
/**
* (多层)xml格式字符串转换为map
*
* @param xml xml字符串
* @return 第一个为Root节点,Root节点之后为Root的元素,如果为多层,可以通过key获取下一层Map
*/
public static Map<String, Object> multilayerXmlToMap(String xml) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
logger.error("xml字符串解析,失败 --> {}", e);
}
Map<String, Object> map = new HashMap<>();
if (null == doc) {
return map;
}
// 获取根元素
Element rootElement = doc.getRootElement();
recursionXmlToMap(rootElement,map);
return map;
}
/**
* multilayerXmlToMap核心方法,递归调用
*
* @param element 节点元素
* @param outmap 用于存储xml数据的map
*/
@SuppressWarnings("unchecked")
private static void recursionXmlToMap(Element element, Map<String, Object> outmap) {
// 得到根元素下的子元素列表
List<Element> list = element.elements();
int size = list.size();
if (size == 0) {
// 如果没有子元素,则将其存储进map中
outmap.put(element.getName(), element.getTextTrim());
} else {
// innermap用于存储子元素的属性名和属性值
Map<String, Object> innermap = new HashMap<>();
// 遍历子元素
list.forEach(childElement -> recursionXmlToMap(childElement, innermap));
outmap.put(element.getName(), innermap);
}
7、xml转json字符串
/**
* xml字符串转换为json字符串
* @return
*/
public static String xml2Json(){
String xml = "<?xml version=\"1.0\" encoding=\"gbk\"?>" +
"<business>" +
"<body >" +
"<kpzdbs>开票终端标识</kpzdbs>" +
"<fplxdm>发票类型代码</fplxdm>" +
"<fpdm>发票代码</fpdm>" +
"<fphm>发票号码</fphm>" +
"<dylx>打印类型</dylx>" +
"<dyfs>打印方式</dyfs>" +
"<printername>打印机名称</printername>" +
"</body>" +
"</business>";
JSONObject json = XML.toJSONObject(xml);
return json.toString();
}
8、Java对象转map
public static Map<String, Object> objectToMap1(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter != null ? getter.invoke(obj) : null;
map.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
9、Java对象转json字符串
/**
*
* @description: 对象转JSON字符串
* @author: Jeff
* @date: 2019年12月15日
* @param bean
*/
public static void beanToJsonString(User bean) {
String s = JSON.toJSONString(bean);
System.out.println(s);
}
10、Java转jsonObject对象
SONObject jo= (JSONObject) JSONObject.toJSON(javaBean);
11、Java对象转xml
/**
* 将对象直接转换成String类型的 XML输出
*
* @param obj
* @return
*/
public static String convertToXml(Object obj) {
// 创建输出流
StringWriter sw = new StringWriter();
try {
// 利用jdk中自带的转换类实现
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
// 格式化xml输出的格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
// 将对象转换成输出流形式的xml
marshaller.marshal(obj, sw);
} catch (JAXBException e) {
e.printStackTrace();
}
return sw.toString();
}
12、java对象转数组
/**
* 对象转数组
*
* @param obj
* @return
*/
public static byte[] serialize(Object object) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
bytes = CompressUtil.compress(bos.toByteArray());// 在这里对byte压缩
oos.close();
bos.close();
} catch (IOException ex) {
Assert.RuntimeException("Object转byte[]出现错误");
ex.printStackTrace();
}
return bytes;
}
13、map转xml(单层)
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, String> data) throws Exception {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
writer.close();
return output;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
14、(多层)map转换为xml
/**
* (多层)map转换为xml格式字符串
*
* @param map 需要转换为xml的map
* @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
* @return xml字符串
*/
public static String multilayerMapToXml(Map<String, Object> map, boolean isCDATA){
String parentName = "xml";
Document doc = DocumentHelper.createDocument();
doc.addElement(parentName);
String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCDATA);
return formatXML(xml);
}
/**
* multilayerMapToXml核心方法,递归调用
*
* @param element 节点元素
* @param parentName 根元素属性名
* @param map 需要转换为xml的map
* @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
* @return xml字符串
*/
@SuppressWarnings("unchecked")
private static String recursionMapToXml(Element element, String parentName, Map<String, Object> map, boolean isCDATA) {
Element xmlElement = element.addElement(parentName);
map.keySet().forEach(key -> {
Object obj = map.get(key);
if (obj instanceof Map) {
recursionMapToXml(xmlElement, key, (Map<String, Object>)obj, isCDATA);
} else {
String value = obj == null ? "" : obj.toString();
if (isCDATA) {
xmlElement.addElement(key).addCDATA(value);
} else {
xmlElement.addElement(key).addText(value);
}
}
});
return xmlElement.asXML();
}
15、map转jsonString
JSONObject jsonObject=JSONObject.fromObject(map);
jsonObject.toString()
16、map转jsonObject
JSONObject jsonObject=JSONObject.fromObject(map);
17、map转Java对象
条件:导入两个包(commons-beanutils-1.9.3.jar
commons-logging-1.1.jar)
/**
* 通过 beanutils 来操作
*
* @param map
* @param user
*/
private static void populate2(Map<String, String> map, User user) {
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
18、map转list
Map<String, String> map = new HashMap<>();
// Convert all Map keys to a List
List<String> result = new ArrayList(map.keySet());
// Convert all Map values to a List
List<String> result2 = new ArrayList(map.values());
// Java 8, Convert all Map keys to a List
List<String> result3 = map.keySet().stream()
.collect(Collectors.toList());
// Java 8, Convert all Map values to a List
List<String> result4 = map.values().stream()
.collect(Collectors.toList());
// Java 8, seem a bit long, but you can enjoy the Stream features like filter and etc.
List<String> result5 = map.values().stream()
.filter(x -> !"apple".equalsIgnoreCase(x))
.collect(Collectors.toList());
// Java 8, split a map into 2 List, it works!
// refer example 3 below
19、jsonObject转jsonString
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "wjw");
jsonObject.put("age", 22);
jsonObject.put("sex", "男");
jsonObject.put("school", "商职");
String jsonStr = JSONObject.toJSONString(jsonObject);
System.out.println(jsonStr);
20、jsonObject转Java对象
String userString = "{"id":1,"name","lz"}";
JSONObject userJson = JSONObject.parseObject(userString);
User user = JSON.toJavaObject(userJson,User.class);
21、jsonObject转map
SONObject obj = new JSONObject();
{
obj.put("key1", "value1");
obj.put("key2", "value2");
obj.put("key3", "value3");
}
Map<String, String> params = JSONObject.parseObject(obj.toJSONString(), new TypeReference<Map<String, String>>(){});