java中json转xml,xml转json

package com.example.demo.controller;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import net.minidev.json.JSONObject;
import org.json.JSONException;
//import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

/**
 * @author LSY
 * @DATE 2023/7/25 20:07
 */
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class jsonToXML {
   public static void main(String[] args) throws JSONException {
      /**
       * @Description:json样例
       * @Author: LSY
       * @Date: 2023/7/25 20:08
       * @param null:
       * @return: null
       **/
    /*
    {
        "name": "lsy",
        "sex": "female",
        "age": 26,
        "location": "ShangHai"
    }*/
//      json转xml
      JSONObject jsonObject=new JSONObject();
      jsonObject.put("name","lsy");
      jsonObject.put( "age", 26);
      jsonObject.put("location", "ShangHai");
      ObjectMapper objectMapper=new ObjectMapper();
      XmlMapper xmlMapper=new XmlMapper();
      JsonNode jsonNode=null;
      String xml=null;
      try {
         jsonNode = objectMapper.readTree(jsonObject.toString());
         xml= xmlMapper.writer().withRootName("Info").writeValueAsString(jsonNode);
         System.out.println("xml="+xml);
      } catch (JsonProcessingException e) {
         e.printStackTrace();
      }

      //xml转json
      JsonNode jsonNode1=null;
      try {
        jsonNode1= xmlMapper.readTree(xml.getBytes());
      } catch (IOException e) {
         e.printStackTrace();
      }
      System.out.println("jsonNode1"+jsonNode1);
   }


}

你可能感兴趣的:(java,json,xml,JSON转XML,XML转JSON)