当前位置: 首页>前端>正文

json转换工具类spring java json转换工具

一种轻量级的数据交换格式。它基于JavaScript的一个子集。后来就很少用到了,后来开始使用Easyui ,就不得不跟Json打交道了。但是也一直没有整理过有关Json的相关知识。直到最近,在做一个项目,前台要求特别高,仅仅是easyui提供的方法已经没有办法满足需求,所以对jquery ,json ,又好好的使用了一次。这次让我收获很大。接下来就跟大家分享一下java中解析json的工具有哪些。

    现在我知道了主要有三种:json-lib,jackson,fastjson。其中json-lib 算是比较早的了。这次项目中使用的也是json-lib ,先跟大家分享一下json-lib的使用。

Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象。

    这里主要是用到了json的两个类:jsonObjec 和jsonArray 。

JSONObject是将Java对象转换成一个json的Object形式,JSONArray是将一个Java对象转换成json的Array格式。

那什么是json的Object形式、Array形式?

用通俗易懂的方法将,所谓的json的Object形式就是一个花括号里面存放的如JavaMap的键值对,如:{name:’hoojo’, age: 24};

那么json的Array形式呢?

就是中括号,括起来的数组。如:[ ‘json’, true, 22];

一、使用前提   

     首先要去官方下载json-lib工具包

    下载地址:http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/

    目前最新的是2.4的版本,本示例中使用的是v2.3;json-lib还需要以下依赖包:

jakarta commons-lang 2.5

jakarta commons-beanutils 1.8.0

jakarta commons-collections 3.2.1

jakarta commons-logging 1.1.1

ezmorph 1.0.6      

官方网址:http://json-lib.sourceforge.net/

然后将这些Jar拷贝到web-info 下的lib中。

  二、javaBean     

<span style="font-family:KaiTi_GB2312;font-size:18px;">@Entity
@Table(name = "job_content_detail")
public class JobContentDetail implements BaseEntity {
    <span >	</span>@Id
	@GeneratedValue(generator = "uuid")
	@GenericGenerator(name = "uuid", strategy = "uuid.hex")
	@Column(name = "ID", length = 32, nullable = false)
	private String id;

	@Column(name = "TS", length = 20, nullable = true)
	private String ts;

	@Column(name = "DR", length = 10, nullable = true)
	private Integer dr;

	@Column(name = "JOBCONTENTMAINID", length = 32, nullable = true)
	private String jobcontentmainid;

	@Column(name = "PRODUCTID", length = 32, nullable = true)
	private String productid;

	@Column(name = "PRODUCTUSAGE", length = 22, precision = 10, nullable = true)
	private String productusage;

	@Column(name = "ITEMQTY", length = 22, precision = 10, nullable = true)
	private Double itemqty;

	@Column(name = "BUILDERQTY", length = 22, precision = 10, nullable = true)
	private Double builderqty;

	@Column(name = "LABOURUNITID", length = 22, precision = 10, nullable = true)
	private String labourunitid;

	@Column(name = "LABOURFACTOR", length = 22, precision = 10, nullable = true)
	private Double labourfactor;
	
	@Column(name = "LABOURFACTOR2", length = 22, precision = 10, nullable = true)
	private Double labourfactor2;
	
	@Column(name = "LABOURFACTOR3", length = 22, precision = 10, nullable = true)
	private Double labourfactor3;

	@Column(name = "ManHours", length = 22, precision = 10, nullable = true)
	private Double manhours;

	@Column(name = "LabourRate", length = 22, precision = 10, nullable = true)
	private Double labourrate;

	@Column(name = "Total", length = 22, precision = 10, nullable = true)
	private Double total;

	@Column(name = "MATERIALUNITID", length = 32, nullable = true)
	private String materialunitid;

	@Column(name = "WASTEFACTOR", length = 22, precision = 10, nullable = true)
	private Double wastefactor;

	@Column(name = "MATERIALTOTAL", length = 22, precision = 10, nullable = true)
	private Double materialtotal;

	@Column(name = "MARERIALRATE", length = 22, precision = 10, nullable = true)
	private Double marerialrate;

	@Column(name = "MANUALLYKEYED", length = 2, nullable = true)
	private String manuallykeyed;

	@Column(name = "PRODUCTRATE", length = 22, precision = 10, nullable = true)
	private Double productrate;

	@Column(name = "PRODUCTMANUALENTRY", length = 150, nullable = true)
	private String productmanualentry;

	@Column(name = "LevelOfDifficulty", length = 22, precision = 10, nullable = true)
	private Double levelofdifficulty;

	@Column(name = "MATERIALQTY", length = 22, precision = 10, nullable = true)
	private Double materialqty;

	@Column(name = "MATERIALBUILDERQTY", length = 22, precision = 10, nullable = true)
	private Double materialbuilderqty;

	@Column(name = "MERCHANT1PRICE", length = 22, precision = 10, nullable = true)
	private Double merchant1price;

	@Column(name = "MERCHANT2PRICE", length = 22, precision = 10, nullable = true)
	private Double merchant2price;

	@Column(name = "MERCHANT3PRICE", length = 22, precision = 10, nullable = true)
	private Double merchant3price;

	@Column(name = "MERCHANT4PRICE", length = 22, precision = 10, nullable = true)
	private Double merchant4price;

	@Column(name = "MATERIALADJUSTMENT", length = 22, precision = 10, nullable = true)
	private Double materialadjustment;

	@Column(name = "SubContractorLabour", length = 2, nullable = true)
	private String subcontractorlabour;

	@Column(name = "SubContractorMaterial", length = 2, nullable = true)
	private String subcontractormaterial;
	
	@Column(name = "ProductName", length = 1000, nullable = true)
	private String productname;

	@Column(name="productcode",length=10,nullable=true)
	 private String productcode;
    <span >	</span>//省略ge,set 方法,
}</span>



JSON对象反序列化成java 对象/集合

    使用json-lib 需要引入如下包:

<span style="font-family:KaiTi_GB2312;font-size:18px;">import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONFunction;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;
import net.sf.json.xml.XMLSerializer;</span>


 这些根据需要引入,并不是全部引入。

1、将JSON字符串 转换成   javaObject

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span >	</span>@Override
	@RequestMapping("/save.do")
	@ResponseBody
	public Object save(HttpServletRequest request) {
		//获取编辑数据 这里获取到的是json字符串
		String inserted = request.getParameter("newRow");</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"><span >		</span>// 要转换的javabean
		JobContentDetail detail = new JobContentDetail();</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"><span >		</span>//如果json 字符串不为空,就进行转化
		if(inserted != null){
		// 把string 转换成jsonObject
		JSONObject jsonobj = JSONObject.fromObject(inserted); </span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"><pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 21px;"><span >		</span>//把json字符串转换成对象<span style="font-family: 'Microsoft YaHei UI', 'Microsoft YaHei', SimSun, 'Segoe UI', Tahoma, Helvetica, sans-serif, 'Microsoft YaHei', Georgia, Helvetica, Arial, sans-serif, 宋体, PMingLiU, serif;"> </span></span>


detail = (JobContentDetail)JSONObject.toBean(jsonobj, JobContentDetail.class); try {labourservice.saveEntity(detail);} catch (Exception e) {e.printStackTrace();return createErrorMessage(e.getMessage()).toString();}}return createSuccessMessage("操作成功!").toString();}



         2、jsonArray  转换成 java list

     具体代码和jsonObject转换成javabean一样,唯独不同的是,转javabean使用的是tobean,转list使用的是 toCollection.   

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span >	</span>JSONArray array =JSONArray.fromObject(ens.toString());
	@SuppressWarnings("unchecked")
	List<JobContentDetail> listDetail=(List<JobContentDetail>)JSONArray.toCollection(array, JobContentDetail.class);</span>



四、java 对象/集合序列化成json      

      个人感觉,将javaBean /list 转换成json比较容易。咱们一步一步来看代码,首先是测试的一些准备代码如下:

<span style="font-family:KaiTi_GB2312;font-size:18px;">@SuppressWarnings({ "deprecation", "unchecked" })
public class JsonlibTest {
    private JSONArray jsonArray = null;
    private JSONObject jsonObject = null;    
    private Student bean = null;    
    @Before
    public void init() {
        jsonArray = new JSONArray(); 
        jsonObject = new JSONObject();        
        bean = new Student();
        bean.setAddress("address");
        bean.setEmail("email");
        bean.setId(1);
        bean.setName("haha");
        Birthday day = new Birthday();
        day.setBirthday("2010-11-22");
        bean.setBirthday(day);
    }    
    @After
    public void destory() {
        jsonArray = null;
        jsonObject = null;
        bean = null;
        System.gc();
    }    
    public final void fail(String string) {
        System.out.println(string);
    }    
    public final void failRed(String string) {
        System.err.println(string);
    }    
}</span>

开始正式我们的调用转换,

        1、首先是javabean 转换成json ,    

<span style="font-family:KaiTi_GB2312;font-size:18px;">    fail("==============Java Bean >>> JSON Object==================");
    fail(JSONObject.fromObject(bean).toString());
    fail("==============Java Bean >>> JSON Array==================");
    fail(JSONArray.fromObject(bean).toString());//array会在最外层套上[]
    fail("==============Java Bean >>> JSON Object ==================");
    fail(JSONSerializer.toJSON(bean).toString());</span>


      输出的结果是: 

==============Java Bean >>> JSON Object==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
==============Java Bean >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]
==============Java Bean >>> JSON Object ==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}


 

   2、javalist 转换成json        

<span style="font-family:KaiTi_GB2312;font-size:18px;">@Test
public void writeList2JSON() {
    fail("==============Java List >>> JSON Array==================");
    List<Student> stu = new ArrayList<Student>();
    stu.add(bean);
    bean.setName("jack");
    stu.add(bean);
    fail(JSONArray.fromObject(stu).toString());
    fail(JSONSerializer.toJSON(stu).toString());
}</span>


       运行后的输出结果为:

      


==============Java List >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]


         如果仔细看代码,会发现一个现象,在javabean转换成json对象的时候,我们也可以使用jsonarray将javaben转换成 jsonarray 。并不是说转换成jsonarray的必须是一个list,它可以是一个kjavabean. 

         如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。

    json-lib 还可以进行xml 和 javabean之间的转化,但是我还没有使用到


https://www.xamrdz.com/web/2l31951478.html

相关文章: