天天看點

FastJson 操作JSON字元串

一、javabean反射工具類,可以在控制台中輸出一個對象的屬性值清單

public class ReflectionUtil {

public static boolean isShow = true; //是否啟用

@SuppressWarnings("unchecked")

public static void getFieldValue(Object obj){

if (isShow) getFieldValue(obj, isShow);

}

@SuppressWarnings("unchecked")

private static void getFieldValue(Object obj,boolean isShow){

Class cls = obj.getClass();

        Method[] methods = cls.getDeclaredMethods();//獲得類的方法集合

        StringBuffer buffer = new StringBuffer();

        try {

        for (Method method : methods) {

if(method!=null && method.getName().startsWith("get")){

Object value = method.invoke(obj, null);

value = method.getName().substring(3)+":"+value+","; 

buffer.append(value);

}

}

        } catch (Exception e) {

        e.printStackTrace();

        }

        System.out.println(cls.toString()+"["+buffer.toString()+"]");

}

public static void main(String[] args) {

}

}

二、F盤的屬性檔案内容

### fastjs### fastjson操作JSON ###

json1={"name":"cena","age":"35","sex":"男"}

json2=[{"name":"cena","age":"35","sex":"男"},{"name":"hhh","age":"37","sex":"男"},{"name":"ever","age":"25","sex":"女"}]

json3={"name":"cena","age":"35","sex":"男","hobbies":[{"name":"踢球","hYear":"2年"},{"":"","":""}]}

三、FastJson工具類

import java.util.ArrayList;

import java.util.List;

import java.util.Properties;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.ttpod.slt.model.Hobby;

import com.ttpod.slt.model.User;

public class JsonUtil {

public static Object parseJavaObject(String jsonStr,Class clazz){

return JSON.toJavaObject(JSON.parseObject(jsonStr), clazz);

}

public static void main(String[] args) {

//0.0加載屬性檔案(所有json字元串從檔案中讀取)

Properties pp = PropertiesUtil.getProperties("f:/properties.properties");

//0.1簡單格式的json字元串

String json1 = pp.getProperty("json1"); 

System.out.println(json1);

User user = (User)JsonUtil.parseJavaObject(json1,User.class);

ReflectionUtil.getFieldValue(user);

//0.2數組形式的json字元串

String json2 = pp.getProperty("json2"); 

System.out.println(json2);

JSONArray array = JSONArray.parseArray(json2);

List<User> userList = new ArrayList<User>();

for(int i = 0; i < array.size();i++){

JSONObject jobj = (JSONObject)array.get(i);

User user2 = JSON.toJavaObject(jobj,User.class);

userList.add(user2);

}

for(User u : userList){

ReflectionUtil.getFieldValue(u);

}

//0.3複雜數組形式的json字元串

String json3 = pp.getProperty("json3");

System.out.println(json3);

User user3 = (User)JsonUtil.parseJavaObject(json3, User.class);

ReflectionUtil.getFieldValue(user3);

for(Hobby h : user3.getHobbies()){

ReflectionUtil.getFieldValue(h);

}

}

}