1. 程式人生 > >java 高階:第三章 json

java 高階:第三章 json

1.判斷字串是否為json字串:(注意:net.sf.json.util.JSONTokener)

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

/**
 * 判斷字串是否為json字串
 * @author wslixiaoliang
 */
public class CheckIsJson
{
    private static Logger logger = LoggerFactory.getApplicationLog(CheckIsJson.class);

    /**
     * 判斷字串是否為json字串
     * @param jsonstr
     * @return
     */
    public static boolean isJson(String jsonstr)
    {
        try
        {
            Object json = new JSONTokener(jsonstr).nextValue();
            if(json instanceof JSONObject)
            {
                return true;
            }
            else if(json instanceof JSONArray)
            {
                return true;
            }
            else{
                return false;
            }
        }catch(Exception e)
        {
            logger.error(e.getMessage(),e);
            return false;
        }
    }

}

2.json解析(JSONObject:必須是 “{ ”開頭;JSONArray:必須是 “[ ”開頭)

//解析json物件
    private static String getJsonValue(String anantationValue)
    {
        String anantation = "";
        if(StringUtil.isNotEmpty(anantationValue) && isJson(excepValueFromJsonString))
        {
            JSONObject jsonObject = JSONObject.fromObject(anantationValue);
            if(null!=jsonObject && jsonObject.containsKey("annotation"))
            {
                anantation = String.valueOf(jsonObject.get("annotation"));
            }
        }
        return anantation;
    }

    //解析jsons陣列
    public String getExcepValueFromJsonString(String excepValueFromJsonString) {
        String excepValue="";
        StringBuilder sub = new StringBuilder();
        if (StringUtil.isNotEmpty(excepValueFromJsonString)&& isJson(excepValueFromJsonString)) {
            JSONArray jsonArray = JSONArray.fromObject(excepValueFromJsonString);
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (null != jsonObject && jsonObject.containsKey("excepValue")) {
                        excepValue = String.valueOf(jsonObject.get("excepValue"));
                        if(sub.length() > 0)
                        {
                            sub.append(",").append(excepValue);
                        }else{
                            sub.append(excepValue);
                        }
                    }
                }
            }
        }
        return sub.toString();
    }