关于JSON一些小例子

public class Jsons {
	public static void main(String[] args) {
 String jsonStr = "{\"result\":[{\"age\":24,\"list\":[{\"cource\":\"90\",\"name\":\"math\"},{\"cource\":\"92\",\"name\":\"english\"}],\"name\":\"jack\",\"sex\":\"male\"},{\"age\":25,\"list\":[{\"cource\":\"100\",\"name\":\"math\"},{\"cource\":\"89\",\"name\":\"politicy\"}],\"name\":\"tom\",\"sex\":\"male\"}]}";
		String stuList = "[{\"age\":24,\"list\":[{\"cource\":\"90\",\"name\":\"math\"},{\"cource\":\"92\",\"name\":\"english\"}],\"name\":\"jack\",\"sex\":\"male\"},{\"age\":25,\"list\":[{\"cource\":\"100\",\"name\":\"math\"},{\"cource\":\"89\",\"name\":\"politicy\"}],\"name\":\"tom\",\"sex\":\"male\"}]";
		String ms = "{\"age\":24,\"list\":[{\"cource\":\"90\",\"name\":\"math\"},{\"cource\":\"92\",\"name\":\"english\"}],\"name\":\"jack\",\"sex\":\"male\"}";

		Jsons t = new Jsons();
		t.convertBean();
		t.convertMap();
		t.convertArray();
		t.convertArray2(stuList);
		t.buildJSon();
		t.jsonListToList(stuList);
	}

	// 注:属性必须具备相应的getter或setter方法才能转换成JSON字符串
	// 创建JSON对象方法
	private JSONFunction showName = new JSONFunction(new String[] { "name" },
			"return this.name];");

	// 从字符串中构造json
	public void buildJsonFormStr() {
		String str = "{\"sex\":\"male\",\"name\":\"jack\",\"age\":24}";

		JSONObject json = JSONObject.fromObject(str);
		System.out.println("从字符串中构造json对象:" + json);

		// 获取json中对象的值
		String name = json.getString("name");
		String sex = json.getString("sex");
		int age = json.getInt("age");

		System.out.println("name:" + name);
		System.out.println("sex:" + sex);
		System.out.println("age:" + age);
	}

	// 构造JSon对象
	public void buildJSon() {
		JSONObject json = new JSONObject();

		// 添加属性
		json.accumulate("name", "jack");

		// 添加方法
		JSONFunction showName = new JSONFunction(new String[] { "name" },
				"return this.name];");
		json.accumulate("showName", showName);

		// 添加对象、集合、数组
		Student s1 = new Student("tom", "male", 25);
		Map<String, Object> sh = new HashMap<String, Object>();
		sh.put("stu1", s1);
		json.accumulate("stu", sh);

		System.out.println("构造的Json对象:" + json);

	}

	// 将数组或List转换成Json字符串
	public void convertArray() {
		List<String> list = new ArrayList<String>();
		list.add("welcome");
		list.add("to");
		list.add("xf");
		list.add("accp");

		Student s1 = new Student("jack", "male", 24);
		Coures coures1 = new Coures("math", "90");
		Coures coures2 = new Coures("english", "92");
		Coures coures3 = new Coures("math", "100");
		Coures coures4 = new Coures("politicy", "89");
		Student s2 = new Student("tom", "male", 25);

		List<Coures> list1 = new ArrayList<Coures>();
		list1.add(coures1);
		list1.add(coures2);
		s1.setList(list1);
		;
		List<Coures> list2 = new ArrayList<Coures>();
		list2.add(coures3);
		list2.add(coures4);
		s2.setList(list2);
		;
		Map<String, Object> sh = new HashMap<String, Object>();
		// 添加对象
		sh.put("stu1", s1);
		sh.put("stu2", s2);
		List<Student> sss = new ArrayList<Student>();
		sss.add(s1);
		// sss.add(s2);

		JSONArray json = JSONArray.fromObject(sss);
		System.out.println("list转换成json字符串:" + json);
	}

	public void convertArray2(String set) {
		JSONObject object = JSONObject.fromObject(set);
		Map<String, Class<?>> cmap = new HashMap<String, Class<?>>();
		cmap.put("list", Coures.class);

		Student trafficResInfo = (Student) JSONObject.toBean(object,
				Student.class, cmap);

		List<Coures> list = trafficResInfo.getList();
		for (Coures coures : list) {
			System.out.println(coures.getCource());
		}
	}

	// 将对象(包含另外一个对象列表)列表JSON串转为list
	@SuppressWarnings("unchecked")
	public void jsonListToList(String jsonStr) {
		JSONArray jsonArray = JSONArray.fromObject(jsonStr);

		// 将josn数组转换成对应类的泛型集合
		Collection<Student> userList = JSONArray.toCollection(jsonArray,
				Student.class);

		List<Student> neList = new ArrayList<Student>();
		JSONObject jsonObject;
		Map<String, Class<?>> cmaps;
		Student stu;
		for (Student student : userList) {
			jsonObject = JSONObject.fromObject(student);
			cmaps = new HashMap<String, Class<?>>();
			cmaps.put("list", Coures.class);
			stu = (Student) JSONObject.toBean(jsonObject, Student.class, cmaps);
			neList.add(stu);
		}

	}

	// 将Map集合转化为json字符串
	public void convertMap() {
		Student s1 = new Student("jack", "male", 24);
		Coures coures1 = new Coures("math", "90");
		Coures coures2 = new Coures("english", "92");
		Coures coures3 = new Coures("math", "100");
		Coures coures4 = new Coures("politicy", "89");
		Student s2 = new Student("tom", "male", 25);

		List<Coures> list1 = new ArrayList<Coures>();
		list1.add(coures1);
		list1.add(coures2);
		s1.setList(list1);
		;
		List<Coures> list2 = new ArrayList<Coures>();
		list2.add(coures3);
		list2.add(coures4);
		s2.setList(list2);
		;
		Map<String, Object> sh = new HashMap<String, Object>();
		// 添加对象
		sh.put("stu1", s1);
		sh.put("stu2", s2);
		List<Student> sss = new ArrayList<Student>();
		sss.add(s1);
		sss.add(s2);

		Map<String, Object> maps = new HashMap<String, Object>();
		maps.put("result", sss);

		// //添加属性:
		// sh.put("address","china xf");
		//
		// //添加一个JSON对象方法
		// String func= "function(i){ alert(i);}";
		// sh.put("func", func);

		JSONObject json = JSONObject.fromObject(maps);
		System.out.println("map转换成json字符串:" + json);
	}

	// bean对象转换成为json字符串
	public void convertBean() {
		Student stu = new Student("jack", "male", 24);
		JSONObject json = JSONObject.fromObject(stu);
		System.out.println("对象转换成json字符串:" + json);
	}
}


package Student;

import java.util.ArrayList;
import java.util.List;

public class Student {

	private String name;
	
	private String sex;
	
	private int age;
	
	private List<Coures> list =new ArrayList<Coures>();

	public Student() {
		// TODO Auto-generated constructor stub
	}
	
	public Student(String name, String sex, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	
	@Override
	public String toString() {
		return "Student [name=" + name + ", sex=" + sex + ", age=" + age
				+ ", list=" + list + "]";
	}

	public List<Coures> getList() {
		return list;
	}

	public void setList(List<Coures> list) {
		this.list = list;
	}
	
}

package Student;

public class Coures {
	
	private String name;
	
	private String cource;
	
	public Coures() {
		// TODO Auto-generated constructor stub
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCource() {
		return cource;
	}

	public void setCource(String cource) {
		this.cource = cource;
	}

	public Coures(String name, String cource) {
		super();
		this.name = name;
		this.cource = cource;
	}

	@Override
	public String toString() {
		return "Coures [name=" + name + ", cource=" + cource + "]";
	}
}




package com.json;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * 1:将JavaBean转换成Map、JSONObject
 * 2:将Map转换成Javabean
 * 3:将JSONObject转换成Map、Javabean
 *
 * @author Alexia
 */

public class JsonHelper {
    
    /**
     * 将Javabean转换为Map
     *
     * @param javaBean
     *            javaBean
     * @return Map对象
     */
    public static Map toMap(Object javaBean) {

        Map result = new HashMap();
        Method[] methods = javaBean.getClass().getDeclaredMethods();

        for (Method method : methods) {

            try {

                if (method.getName().startsWith("get")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);

                    Object value = method.invoke(javaBean, (Object[]) null);
                    result.put(field, null == value ? "" : value.toString());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return result;

    }

    /**
     * 将Json对象转换成Map
     *
     * @param jsonObject
     *            json对象
     * @return Map对象
     * @throws JSONException
     */
    public static Map toMap(String jsonString) throws JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);
        
        Map result = new HashMap();
        Iterator iterator = jsonObject.keys();
        String key = null;
        String value = null;
        
        while (iterator.hasNext()) {

            key = (String) iterator.next();
            value = jsonObject.getString(key);
            result.put(key, value);

        }
        return result;

    }

    /**
     * 将JavaBean转换成JSONObject(通过Map中转)
     *
     * @param bean
     *            javaBean
     * @return json对象
     */
    public static JSONObject toJSON(Object bean) {

        return new JSONObject(toMap(bean));

    }

    /**
     * 将Map转换成Javabean
     *
     * @param javabean
     *            javaBean
     * @param data
     *            Map数据
     */
    public static Object toJavaBean(Object javabean, Map data) {

        Method[] methods = javabean.getClass().getDeclaredMethods();
        for (Method method : methods) {

            try {
                if (method.getName().startsWith("set")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("set") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    method.invoke(javabean, new Object[] {

                    data.get(field)

                    });

                }
            } catch (Exception e) {
            }

        }

        return javabean;

    }

    /**
     * JSONObject到JavaBean
     *
     * @param bean
     *            javaBean
     * @return json对象
     * @throws ParseException
     *             json解析异常
     * @throws JSONException
     */
    public static void toJavaBean(Object javabean, String jsonString)
            throws ParseException, JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);
    
        Map map = toMap(jsonObject.toString());
        
        toJavaBean(javabean, map);

    }

}



package com.json;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 使用json-lib构造和解析Json数据
 *
 * @author Alexia
 * @date 2013/5/23
 *
 */
public class OrgJsonTest {

    /**
     * 构造Json数据
     *
     * @return
     * @throws JSONException
     */
    public static String BuildJson() throws JSONException {

        // JSON格式数据解析对象
        JSONObject jo = new JSONObject();

        // 下面构造两个map、一个list和一个Employee对象
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("name", "Alexia");
        map1.put("sex", "female");
        map1.put("age", "23");

        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("name", "Edward");
        map2.put("sex", "male");
        map2.put("age", "24");

        List<Map> list = new ArrayList<Map>();
        list.add(map1);
        list.add(map2);

        Employee employee = new Employee();
        employee.setName("wjl");
        employee.setSex("female");
        employee.setAge(24);

        // 将Map转换为JSONArray数据
        JSONArray ja = new JSONArray();
        ja.put(map1);

        System.out.println("JSONArray对象数据格式:");
        System.out.println(ja.toString());

        // 将Javabean转换为Json数据(需要Map中转)
        JSONObject jo1 = JsonHelper.toJSON(employee);

        System.out.println("\n仅含Employee对象的Json数据格式:");
        System.out.println(jo1.toString());

        // 构造Json数据,包括一个map和一个含Employee对象的Json数据
        jo.put("map", ja);
        jo.put("employee", jo1.toString());
        System.out.println("\n最终构造的JSON数据格式:");
        System.out.println(jo.toString());

        return jo.toString();

    }

    /**
     * 解析Json数据
     *
     * @param jsonString
     *            Json数据字符串
     * @throws JSONException
     * @throws ParseException
     */
    public static void ParseJson(String jsonString) throws JSONException,
            ParseException {

        JSONObject jo = new JSONObject(jsonString);
        JSONArray ja = jo.getJSONArray("map");

        System.out.println("\n将Json数据解析为Map:");
        System.out.println("name: " + ja.getJSONObject(0).getString("name")
                + " sex: " + ja.getJSONObject(0).getString("sex") + " age: "
                + ja.getJSONObject(0).getInt("age"));

        String jsonStr = jo.getString("employee");
        Employee emp = new Employee();
        JsonHelper.toJavaBean(emp, jsonStr);

        System.out.println("\n将Json数据解析为Employee对象:");
        System.out.println("name: " + emp.getName() + " sex: " + emp.getSex()
                + " age: " + emp.getAge());

    }

    /**
     * @param args
     * @throws JSONException
     * @throws ParseException
     */
    public static void main(String[] args) throws JSONException, ParseException {
        // TODO Auto-generated method stub

        ParseJson(BuildJson());
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值