代码:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class Xml2Json {
public static void main(String[] args) {
String xml = null;
try {
xml = FileUtils.readFileToString(new File("E:\\code\\test\\1.xml"));
System.out.println(org.json.XML.toJSONObject(xml).toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
备注:
maven项目,需要导入响应的包
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
转换前:
<?xml version="1.0" encoding="utf-8"?>
<Message>
<PolicyList>
<PolicyDetail>
<Apply>
<ApplyNo>2017121212100001</ApplyNo>
<ApplicationNo>2017121212100003</ApplicationNo>
<Status>3</Status>
<PolicyAmount>50000.00</PolicyAmount>
<Premium>5.67</Premium>
</Apply>
<Holder>
<Name>aaa</Name>
<CertType>1</CertType>
<CertNo>sdsd</CertNo>
<Mobile>dfdf</Mobile>
</Holder>
<InsuredList>
<Insured>
<Name>查</Name>
<CertType>1</CertType>
<CertNo>sdsd</CertNo>
<Mobile>dfdf</Mobile>
<Address>sdsd</Address>
</Insured>
<Insured>
<Name>哈哈</Name>
<CertType>1</CertType>
<CertNo>sdsd</CertNo>
<Mobile>dfdf</Mobile>
<Address>sdsd</Address>
</Insured>
</InsuredList>
<Vehicle>
<LicensePlateNo>沪A 12345</LicensePlateNo>
<LicensePlateType>02</LicensePlateType>
<MotorTypeCode>11</MotorTypeCode>
<MotorUsageTypeCode>200</MotorUsageTypeCode>
</Vehicle>
</PolicyDetail>
</PolicyList>
<Sign>W05YVZk6J6CyIqnmLjbDpvNVfKXp8NXGchPSAWZuVCR2PM6J34QRdTIHiNsYlHZWtrQcVASe48bPEZ8+VU6U3iLs1EmJdJWX0fZdaf+yeA3K966G1xY3xgJB2BNoyYt1EB27I0P7fxx+VRZdfPELm86x+ItTxrWli8xWAA+Qnn0=</Sign>
</Message>
转换后:
{
"Message": {
"PolicyList": {
"PolicyDetail": {
"Vehicle": {
"LicensePlateNo": "沪A 12345",
"MotorTypeCode": 11,
"LicensePlateType": "02",
"MotorUsageTypeCode": 200 },
"Apply": {
"Status": 3,
"ApplicationNo": 2017121212100003,
"PolicyAmount": 50000,
"Premium": 5.67,
"ApplyNo": 2017121212100001 },
"Holder": {
"CertType": 1,
"CertNo": "sdsd",
"Mobile": "dfdf",
"Name": "aaa" },
"InsuredList": {
"Insured": [{ "Address": "sdsd", "CertType": 1, "CertNo": "sdsd", "Mobile": "dfdf", "Name": "查" }, { "Address": "sdsd", "CertType": 1, "CertNo": "sdsd", "Mobile": "dfdf", "Name": "哈哈" }] }
}
},
"Sign": "W05YVZk6J6CyIqnmLjbDpvNVfKXp8NXGchPSAWZuVCR2PM6J34QRdTIHiNsYlHZWtrQcVASe48bPEZ8+VU6U3iLs1EmJdJWX0fZdaf+yeA3K966G1xY3xgJB2BNoyYt1EB27I0P7fxx+VRZdfPELm86x+ItTxrWli8xWAA+Qnn0="
}
}
注意:
需要注意的是List是否是自己想要的格式