在Java中,可以使用第三方庫(如Jackson、Gson、org.json等)來實現JSON與XML之間的相互轉換。
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class JsonToXmlConverter {
public static String convertJsonToXml(String json) {
try {
ObjectMapper objectMapper = new ObjectMapper();
XmlMapper xmlMapper = new XmlMapper();
Object jsonObject = objectMapper.readValue(json, Object.class);
return xmlMapper.writeValueAsString(jsonObject);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class XmlToJsonConverter {
public static String convertXmlToJson(String xml) {
try {
ObjectMapper objectMapper = new ObjectMapper();
XmlMapper xmlMapper = new XmlMapper();
Object xmlObject = xmlMapper.readValue(xml, Object.class);
return objectMapper.writeValueAsString(xmlObject);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
使用Gson庫也可以實現JSON與XML之間的相互轉換,具體方法可以參考Gson的官方文檔。