json-lib把XML转化为json

1,依赖的jar包

	<dependency>
  		<groupId>net.sf.json-lib</groupId>
  		<artifactId>json-lib</artifactId>
  		<version>2.4</version>
  		<classifier>jdk15</classifier>
  	</dependency>
  	<dependency>
  <groupId>xom</groupId>
  <artifactId>xom</artifactId>
  <version>1.2.5</version>
</dependency>

<dependency>
  <groupId>xom</groupId>
  <artifactId>xom</artifactId>
  <version>1.2.5</version>
  <classifier>sources</classifier>
</dependency>

 

2,实例

@Test
	public void test04() throws FileNotFoundException{
		XMLSerializer xmlSerializer = new XMLSerializer();
		
		xmlSerializer.setSkipWhitespace(false);//tObjectName("com.jn.json.bean.OrderResultResp");

		InputStream ins=new FileInputStream("E:\\tmp\\orderResultRet.txt");
		JSON jsonObj=xmlSerializer.readFromStream(ins);//adFromFile("E:\\tmp\\orderResultRet.txt");
//		JSON jsonObj=xmlSerializer.read(str);
		String jsonStr=jsonObj.toString();
		System.out.println(jsonStr);
		
	}

 运行结果:

{"head":{"signType":"2","version":"v1.0"},"body":{"businessId":"00WGCX210027","platIdtfy":"t3","merchantId":"0044098","orderId":"2015070500017","orderDate":"20150705","detailId":[],"detailTime":"2015-07-05 15:42:35","bankId":[],"bankDealId":[],"amount":"1","amt_type":"01","payResult":"00","errCode":[],"errMsg":[],"payeeBankAccount":[],"payeeBankType":[],"payeeBankName":[],"payeeName":[],"deviceId":[],"signMsg":"b56fd6c113db486bda4d7823041de638"}}

 

但是有个问题:xml中没有值得竟然变成了空数组([])

解决方法:

jsonStr=jsonStr.replace("[]", "\"\"");

优化之后的程序:

@Test
	public void test04() throws FileNotFoundException{
		XMLSerializer xmlSerializer = new XMLSerializer();
		
		xmlSerializer.setSkipWhitespace(false);//tObjectName("com.jn.json.bean.OrderResultResp");

		InputStream ins=new FileInputStream("E:\\tmp\\orderResultRet.txt");
		JSON jsonObj=xmlSerializer.readFromStream(ins);//adFromFile("E:\\tmp\\orderResultRet.txt");
		String jsonStr=jsonObj.toString();
		jsonStr=jsonStr.replace("[]", "\"\"");
		System.out.println(jsonStr);
		
	}

 

 

 

你可能感兴趣的:(读取xml,xml转json)