在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的官方文档。