Jackson工具,java对象和json字符串之间的互相转换

一、maven依赖引入jackson

		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.5</version>
        </dependency>

在这里插入图片描述
jackson-databind依赖见下:

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>

二、JsonUtil工具类

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * Json encode
     *
     * @param object object
     * @return String
     */
    public static String encode(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json encode failed!", e);
        }
    }

    /**
     * Json decode
     *
     * @param json          json
     * @param typeReference typeReference
     * @param <T>           T
     * @return T
     */
    public static <T> T decode(String json, TypeReference<T> typeReference) {
        try {
            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (Exception e) {
            throw new RuntimeException("Json decode failed!", e);
        }
    }

    /**
     * Json decode
     *
     * @param json        json
     * @param targetClass targetClass
     * @param <T>         T
     * @return T
     */
    public static <T> T decode(String json, Class<T> targetClass) {
        try {
            return OBJECT_MAPPER.readValue(json, targetClass);
        } catch (Exception e) {
            throw new RuntimeException("Json decode failed!", e);
        }
    }
}

三、使用示例

定义一个User对象

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class User {
        private String name;
        private Integer age;
    }
  • encode() 单个对象
String str = JsonUtil.encode(new User("张三", 10));

// {"name":"张三","age":10}
System.out.println(str);
  • encode() 对象集合
   List<User> userList  = Lists.newArrayList();
   userList.add(new User("张三", 10));
   userList.add(new User("李四", 12));
       
   String str = JsonUtil.encode(userList);
   
   // [{"name":"张三","age":10},{"name":"李四","age":12}]
   System.out.println(str);    
  • decode() 单个对象
   String json = "{\"name\":\"stelin\",\"age\":18}";
   User user = JsonUtil.decode(json, User.class);
   
   // JsonUtil.User(name=stelin, age=18)
   System.out.println(user);
  • decode() 对象集合
String str = "[{\"name\":\"张三\",\"age\":10},{\"name\":\"李四\",\"age\":12}]";

List<User> userList = JsonUtil.decode(str, new TypeReference<List<User>>() {
        });
        
// [JsonUtil.User(name=张三, age=10), JsonUtil.User(name=李四, age=12)]
System.out.println(userList);
  • decode() 字符串集合
String str = "[1, 2, 3]";

List<String> list = JsonUtil.decode(str, new TypeReference<List<String>>() {
});

// [1, 2, 3]
System.out.println(list);

很多jar包都会有类TypeReference,别错误地引用了,注意这里的TypeReference是com.fasterxml.jackson.core.type.TypeReference。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,可以使用多种方式将XML字符串转换JSON字符串,或将JSON字符串转换成XML字符串。以下是一些常用的方法: 1. 使用第三方库 常用的XML和JSON转换库有:jackson、Gson、xmlpull、xmlbeans、dom4j、jdom等。这些库提供了各种将XML和JSON字符串互相转换的方法。例如,使用Jackson库将XML字符串转换JSON字符串: ```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; String xmlString = "<person><name>John</name><age>30</age></person>"; // 将XML字符串转换Java对象 XmlMapper xmlMapper = new XmlMapper(); Object obj = xmlMapper.readValue(xmlString, Object.class); // 将Java对象转换JSON字符串 ObjectMapper jsonMapper = new ObjectMapper(); String jsonString = jsonMapper.writeValueAsString(obj); System.out.println(jsonString); ``` 输出结果为: ```json {"person":{"name":"John","age":"30"}} ``` 2. 手动转换 也可以手动编写代码将XML和JSON字符串互相转换。例如,使用Java内置的XML DOM API将XML字符串转换JSON字符串: ```java import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.util.HashMap; import java.util.Map; String xmlString = "<person><name>John</name><age>30</age></person>"; // 将XML字符串解析为DOM对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlString))); // 将DOM对象转换JSON对象 JSONObject json = new JSONObject(); Element root = doc.getDocumentElement(); if (root.hasChildNodes()) { NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Map<String, String> map = new HashMap<>(); if (element.hasAttributes()) { for (int j = 0; j < element.getAttributes().getLength(); j++) { map.put(element.getAttributes().item(j).getNodeName(), element.getAttributes().item(j).getNodeValue()); } } if (element.hasChildNodes()) { json.put(element.getNodeName(), element.getTextContent()); } else if (!map.isEmpty()) { json.put(element.getNodeName(), new JSONObject(map)); } } } } System.out.println(json.toString()); ``` 输出结果为: ```json {"person":{"name":"John","age":"30"}} ``` 3. 使用XPath表达式 我们还可以使用XPath表达式从XML中提取数据,并将其转换JSON格式。例如,使用Java内置的XPath API将XML字符串转换JSON字符串: ```java import org.json.JSONObject; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.StringReader; String xmlString = "<person><name>John</name><age>30</age></person>"; // 创建XPath对象 XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // 编译XPath表达式 XPathExpression expr = xpath.compile("/*"); // 将XML字符串解析为DOM对象 InputSource source = new InputSource(new StringReader(xmlString)); NodeList nodes = (NodeList) expr.evaluate(source, XPathConstants.NODESET); // 将DOM对象转换JSON对象 JSONObject json = new JSONObject(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if (element.hasChildNodes()) { json.put(element.getNodeName(), element.getTextContent()); } } } System.out.println(json.toString()); ``` 输出结果为: ```json {"person":{"name":"John","age":"30"}} ``` 注意:以上示例仅供参考,实际使用时需要根据具体情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天草二十六_简村人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值