当前位置: 首页 > 工具软件 > JSON for .NET > 使用案例 >

json处理之net.sf.json

巴博耘
2023-12-01

1使用net.sf.json ,所在包:json-lib-2.4-jdk15.jar

测试类:

package com.ultimate.ws.api;
// default package


public class Subscriptionevent implements java.io.Serializable {

	private String userId;
	private String countryCode;
	private String subscriptionTier;
	private String paymentType=null;
	private String startDate=null;
	private String expiryDate=null;
	private String transactionId;
	
	private String serviceCode;

	...

}

测试数据:

文件形式:  String filePath="/xxx/test.json";
文件内容:
[{"subscriptionTier":"DELETE","startDate":null,"transactionId":"11111111111111111","paymentType":null,"expiryDate":null,"userId":"1111111111111111","countryCode":"CN","serviceCode":null},{"subscriptionTier":"DELETE","startDate":null,"transactionId":"222222222222222222","paymentType":null,"expiryDate":null,"userId":"22222222222222222222222","countryCode":"CN","serviceCode":null},{"subscriptionTier":"DELETE","startDate":null,"transactionId":"33333333333333333333","paymentType":null,"expiryDate":null,"userId":"333333333333333333333333","countryCode":"CN","serviceCode":null}]

接口所接收的json格式:

{subscriptionEvents:[{"subscriptionTier":"DELETE","startDate":null,"transactionId":"11111111111111111","paymentType":null,"expiryDate":null,"userId":"1111111111111111","countryCode":"CN","serviceCode":null},{"subscriptionTier":"DELETE","startDate":null,"transactionId":"222222222222222222","paymentType":null,"expiryDate":null,"userId":"22222222222222222222222","countryCode":"CN","serviceCode":null},{"subscriptionTier":"DELETE","startDate":null,"transactionId":"33333333333333333333","paymentType":null,"expiryDate":null,"userId":"333333333333333333333333","countryCode":"CN","serviceCode":null}]}

接口调用:

package com.ultimate.ws.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.log4j.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import org.junit.Test;
import com.ultimate.ws.api.Subscriptionevent;
import com.ultimate.ws.util.HttpClientUtil.UTF8PostMethod;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.InputStream;



public class SubscriptionEventTest {
	private static Logger logger = Logger
			.getLogger(SubscriptionEventTest.class);

	

	@Test
	public void sendEvent() {
                //从文件读取数据
		File file = new File("/xxx/test.json");		
		String contents = "";
		JsonConfig jsonConfig= new JsonConfig();  
                //在把字符串转为json对象时,设置字符串值如果为null时就是null,不要默认转成""
		jsonConfig.registerDefaultValueProcessor(String.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		try {
                        //读取文件--流数据---读入字节数组---转为字符串
			InputStream in = new FileInputStream(file);
			int len = (int) file.length();
			byte[] buffer = new byte[len];
			in.read(buffer, 0, len);
			contents = new String(buffer);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//此处测试数据为数组格式,使用JSONArray
		JSONArray arr = JSONArray.fromObject(contents);
		List<Subscriptionevent> list = new ArrayList<Subscriptionevent>();
		String url = "/xxx/posturl";
		for (int i = 0; i < arr.size(); i++) {
			//逐个获取每个对象
			Object a00 = arr.get(i);
			JSONObject a0=JSONObject.fromObject(a00);
			Subscriptionevent a=(Subscriptionevent) JSONObject.toBean(a0,  Subscriptionevent.class);
			list.add(a);
		}
		if (list.size() > 0) {
                        //json对象---字符串的转换,这里
			JSONArray b = JSONArray.fromObject(list,jsonConfig);
			//JsonConfig config = new JsonConfig();
			//config.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
			//String[] EXCLUDES = new String[]{"createDate","createUser","modifyDate","modifyUser","resultCode","resultMsg","id"};
                      // config.setExcludes(EXCLUDES);  //可设置排除某些字段
                       生成的对象是和原来的文件里的内容一样,这里遍历可以对其做些修改,我原始初衷,做这层遍历是因为接口处理中使用的json处理类不支持一次性调用时数组对象的内容过大,似乎是对大小做了限制,一旦超过设定的大小就自动截断,导致解析时格式异常。这里为了展示net.sf.json的使用把中间的将原始list拆分成多个发送的逻辑给去掉了。
                       //这里是要在原json的外面再包裹一个key,最简单的方式就是下面这样的字符串拼接,另一种方式就是创建一个java pojo对象,里面只包含一个类型为list的元素
			String ss ="{subscriptionEvents:"+ b.toString()+"}";
                        //简单的调用接口,可以使用firefox的插件RestClient,或者使用下面这样的用程序接口调用的方式
			HttpClient httpClient = new HttpClient();
			UTF8PostMethod postMethod = new UTF8PostMethod(url);
			byte[] b2 = null;
			try {
				b2 = ss.getBytes("utf-8");
				InputStream inputStream = new ByteArrayInputStream(b2, 0,
						b2.length);
				RequestEntity requestEntity = new InputStreamRequestEntity(
						inputStream, b2.length);
				postMethod.setRequestEntity(requestEntity);
				httpClient.executeMethod(postMethod);
				String response = postMethod.getResponseBodyAsString();
				postMethod.releaseConnection();
				
				if(!response.contains("success")){
					System.out.println("lsx error:" +ss);
					
				}

				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

总结:

使用此net.sf.json操作时遇到的问题:

所需jar包

 1、 commons-beanutils-1.8.0.jar不加这个包
    java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean


2、commons-collections-3.1.jar 不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap


3、commons-lang-2.5.jar不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException


4、commons-logging-1.2.jar不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory


5、ezmorph-1.0.6.jar不加这个包
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher


6、json-lib-2.4-jdk15.jar不加这个包
java.lang.NoClassDefFoundError: net/sf/json/JSONObject

 

2 在做转换时net.sf.json.JsonConfig对象,用于设置一些字段,日期,空 等格式等

参考博客: https://www.cnblogs.com/handsomeye/p/5107398.html

3 日期格式Date默认如果不做任何设置的话,再转化为时会成为:{"date":6,"day":3,"hours":21,"minutes":26,"month":0,"nanos":290000000,"seconds":31,"time":1452086791290,"timezoneOffset":-480,"year":116}

所以在处理日期类型的数据时,可以简单的用字符串格式接收,不必再转换了,存数据库时,数据库也是可以自动实现转换的

4 net.sf.json.JSONObject对象使用指南 https://blog.csdn.net/lk142500/article/details/82499387

5 在json字符串中,key可以有引号,也可以不带引号都是对的

{"address":"北京市西城区","age":"23","name":"JSON"}
 {address:"北京市西城区",age:"23",name:"JSON"}
 类似资料: