基于Jackson封装的JSON、Properties、XML、YAML 相互转换的通用方法
import java.io.IOException;
import java.util.Properties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
/**
* JsonNodeUtils 转换工具
*
* @author 00fly
*
*/
public class JsonNodeUtils
{
private static JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
private static JsonMapper jsonMapper = new JsonMapper();
private static XmlMapper xmlMapper = new XmlMapper();
private static YAMLMapper yamlMapper = new YAMLMapper();
// JsonNode对象转换为JSON、PROPERTIES、XML、YAML
/**
* jsonNode转json字符串
*
* @param jsonNode
* @return
*/
public static String jsonNodeToJson(JsonNode jsonNode)
{
return jsonNode.toPrettyString();
}
/**
* jsonNode转properties字符串
*
* @param jsonNode
* @return
* @throws IOException
*/
public static String jsonNodeToPropsText(JsonNode jsonNode)
throws IOException
{
return javaPropsMapper.writeValueAsString(jsonNode);
}
/**
* jsonNode转properties对象
*
* @param jsonNode
* @return
* @throws IOException
*/
public static Properties jsonNodeToProperties(JsonNode jsonNode)
throws IOException
{
return javaPropsMapper.writeValueAsProperties(jsonNode);
}
/**
* jsonNode转xml字符串
*
* @param jsonNode
* @return
* @throws IOException
*/
public static String jsonNodeToXml(JsonNode jsonNode)
throws IOException
{
return xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
}
/**
* jsonNode转yaml
*
* @param jsonNode
* @return
* @throws IOException
*/
public static String jsonNodeToYaml(JsonNode jsonNode)
throws IOException
{
return yamlMapper.writeValueAsString(jsonNode);
}
// JSON、PROPERTIES、XML、YAML转换为JsonNode对象
/**
* json转JsonNode
*
* @param jsonText
* @return
* @throws IOException
*/
public static JsonNode jsonToJsonNode(String jsonText)
throws IOException
{
return jsonMapper.readTree(jsonText);
}
/**
* properties对象转JsonNode
*
* @param properties
* @return
* @throws IOException
*/
public static JsonNode propsToJsonNode(Properties properties)
throws IOException
{
return javaPropsMapper.readPropertiesAs(properties, JsonNode.class);
}
/**
* properties字符串转JsonNode
*
* @param propText
* @return
* @throws IOException
*/
public static JsonNode propsToJsonNode(String propText)
throws IOException
{
return javaPropsMapper.readTree(propText);
}
/**
* xml转JsonNode
*
* @param xmlContent
* @return
* @throws IOException
*/
public static JsonNode xmlToJsonNode(String xmlContent)
throws IOException
{
return xmlMapper.readTree(xmlContent);
}
/**
* yaml转JsonNode
*
* @param yamlContent
* @return
* @throws IOException
*/
public static JsonNode yamlToJsonNode(String yamlContent)
throws IOException
{
return yamlMapper.readTree(yamlContent);
}
}