使用JSONlib简单的转换json操作

在使用jsonlib操作之前 需要引入json及5个依赖包,依赖包版本不能最新,lang与collections有不兼容现象。

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

以下是简单的实例代码,展现了几个转换的基本操作

json --> javabean

javabean --> json

array -->json

map -->json

......

package com.xx.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class TestJsonLib {
	@Override
	public String toString() {
		return "TestJsonLib [name=" + name + ", age=" + age + ", gender=" + gender + "]";
	}
	public TestJsonLib() {
		super();
		// TODO Auto-generated constructor stub
	}
	public TestJsonLib(String name, int age, String gender) {
		super();
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
	private String name = null;
	private int age = 1;
	private String gender = "female";
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public static void main(String[] args){
		
		//JSONObject.fromObject()  转换为json对象
		//JSONObject.toBean() 转换为javabean对象
		
		//json对象 --> String
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("b1", "String01");
		jsonObj.put("b2", "String02");
		jsonObj.put("b3", "String03");
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(jsonObj);
		System.out.println(jsonArray);//[{"b1":"String01","b2":"String02","b3":"String03"}]
		
		//数组转化为json格式,list也是一种数组格式
		List<String> list = new ArrayList<>();
		list.add("book1");
		list.add("book2");
		list.add("book3");
		JSONArray arr = JSONArray.fromObject(list);
		System.out.println(arr);//["book1","book2","book3"]
		
		//Map键值对转换为json格式
		Map<String,String> myMap = new HashMap<>();
		myMap.put("book1","javacore");
		myMap.put("book2","thinking in java");
		myMap.put("book3","test java");
		JSONObject obj = JSONObject.fromObject(myMap);
		System.out.println(obj); //{"book3":"test java","book1":"javacore","book2":"thinking in java"}
		
		
		//javabean --> json格式
		JSONObject personInfo = JSONObject.fromObject(new TestJsonLib("Eric",23,"female"));
		System.out.println(personInfo);//{"age":23,"gender":"female","name":"Eric"}
		
		
		//json --> javabean
		String content = "{\"age\":25,\"gender\":\"male\",\"name\":\"Jack\"}";
		JSONObject jsonString = JSONObject.fromObject(content);
		//转换为javabean
		TestJsonLib jsonInfo = (TestJsonLib)JSONObject.toBean(jsonString, TestJsonLib.class);
		System.out.println(jsonInfo);//TestJsonLib [name=Jack, age=25, gender=male]
		
	}

}

  

posted @ 2015-12-28 16:26  WhyToHow  阅读(179)  评论(0编辑  收藏  举报