JSON对象操作一

此处需要引入jar:

fastjson-1.1.15.jar 或者 json-lib-2.3-jdk15.jar

package com.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
 * 需求描述:PC端设计表单在手机端显示,选择需要显示的表单,设计表时简洁。
 * @author sunlight
 *
 */
public class JsonHelper {
	public static void main(String[] args) {
		setApplySetting2JSON();
		
		getObject2JSONObject(setApplySetting2JSON());
		getObject2JSON(setApplySetting2JSON());
	}
	
	/**
	 * 调用常规方法
	 * 把JSON字符串转换成对象(简洁)
	 * com.alibaba.fastjson.JSON;
	 * @param obj
	 */
	public static void getObject2JSONObject(Object obj){
		if(obj==null){
			System.out.println("obj为空!");
		}
		String settingString = obj+"";
		
		List<AppSettings> settings =new ArrayList<AppSettings>();
		
		settings= JSONObject.parseArray(settingString, AppSettings.class);
		 
		for (int i = 0; i < settings.size(); i++) {
			System.out.println(i+"="+settings.get(i).colums);
		}
	}
	
	
	/**
	 * 调用常规方法
	 * 把JSON字符串转换成对象
	 * com.alibaba.fastjson.JSON;
	 * @param obj
	 */
	public static void getObject2JSON(Object obj){
		if(obj==null){
			System.out.println("obj为空!");
		}
		String settingString = obj+"";
		
		List<AppSettings> settings =new ArrayList<AppSettings>();
		
		JSONArray josn=JSON.parseArray(settingString);
		for (int i = 0; i < josn.size(); i++) {
			System.out.println(josn.get(i));
			settings.add(JSON.parseObject(josn.get(i)+"", AppSettings.class));
		}
		for (int i = 0; i < settings.size(); i++) {
			System.out.println(i+"="+settings.get(i).colums);
		}
	}
	
	/**
	 * 调用常规方法
	 * 把对象转换为JSON字符串
	 * com.alibaba.fastjson.JSON;
	 * @return
	 */
	public static Object setApplySetting2JSON(){
		List<AppSettings> settings=new ArrayList<AppSettings>();
		for (int i = 0; i <10; i++) {
			AppSettings setting = new AppSettings();
			setting.colums="colums"+i;
			setting.index=1;
			setting.isSelected=1;
			settings.add(setting);
		}
		Object obj=JSON.toJSON(settings);
		System.out.println("obj="+obj);
		return obj;
	}
}


class AppSettings implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public String colums;
	public int isSelected;
	public int index;
	
	public AppSettings() {
		super();
	}
}

结果如下:


发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *