Java JSON 해석
8532 단어 자바
데이터 형식 지원:String,int,Integer,double,Double,boolean,Boolean,BigDecimal,List,Map
Map key 는 String 이 어야 합 니 다.
데이터 형식의 해석 을 참조 하려 면 맵 맵
package com.json;
/**
* json
* Created by wangxin on 2015/2/14.
*/
public interface JsonParser {
/**
* @param jsonStr
* @return
*/
public JsonResponse parse(String jsonStr) throws Exception;
}
package com.json.parser;
import com.json.JsonParser;
import com.json.JsonResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* , /Bigdecimal
* Created by wangxin on 2015/3/12.
*/
public class SimpleObjectParser implements JsonParser {
private static final String TAG = SimpleObjectParser.class.getSimpleName();
private Class<? extends JsonResponse> responseType;
private Map<String, Class> typeClass;
/**
*
* List Map
* Map key string
*/
private static interface ClassType {
String STRING = "class java.lang.String";
String INT = "int";
String INTEGER = "class java.lang.Integer";
String DOUBLE = "double";
String DOUBLE_CLASS = "class java.lang.Double";
String BOOLEAN = "boolean";
String BOOLEAN_CLASS = "class java.lang.Boolean";
String BIGDECIMAL = "java.math.BigDecimal";
}
public SimpleObjectParser(Class<? extends JsonResponse> responseType) {
this.responseType = responseType;
}
public SimpleObjectParser(Class<? extends JsonResponse> responseType, Map<String, Class> typeClass) {
this.responseType = responseType;
this.typeClass = typeClass;
}
@Override
public JsonResponse parse(String jsonStr) throws Exception {
try {
JSONObject json = JSONObject.fromObject(jsonStr);
return (JsonResponse) parse(json, responseType);
} catch (Exception e) {
// LogUtil.e(TAG, "pase error:" + jsonStr);
throw e;
}
}
/**
* , JSONObject
*
* @param json
* @param classType
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
private Object parse(JSONObject json, Class classType) throws IllegalAccessException, InstantiationException {
if (null == classType)
return null;
Method[] methods = classType.getMethods();
Object result = classType.newInstance();
for (Method m : methods) {
if (!m.getName().startsWith("set") || m.getParameterTypes().length != 1)
continue;
try {
Object param = parseParam(m.getParameterTypes()[0], getPropertyName(m.getName()), json);
if (null != param)
m.invoke(result, param);
} catch (Exception e) {
continue;
}
}
return result;
}
/**
* json
*
* @param type
* @param propertyName
* @param json
* @return
*/
private Object parseParam(Class type, String propertyName, JSONObject json) throws JSONException {
Object param = null;
String typeStr = type.toString();
if (typeStr.equals(ClassType.STRING))
param = json.getString(propertyName);
else if (typeStr.equals(ClassType.INT) || typeStr.equals(ClassType.INTEGER))
param = json.getInt(propertyName);
else if (typeStr.equals(ClassType.DOUBLE) || typeStr.equals(ClassType.DOUBLE_CLASS))
param = json.getDouble(propertyName);
else if (typeStr.equals(ClassType.BOOLEAN) || typeStr.equals(ClassType.BOOLEAN_CLASS))
param = json.getBoolean(propertyName);
else if (typeStr.equals(ClassType.BIGDECIMAL))
param = new BigDecimal(json.getString(propertyName));
else if (List.class.isAssignableFrom(type))
param = parseList(json, propertyName, type);
else if (Map.class.isAssignableFrom(type))
param = parseMap(json, propertyName, type);
else if (typeStr.startsWith("class "))
param = parseObject(json, propertyName);
return param;
}
/**
* set
*
* @param methodName
* @return
*/
private String getPropertyName(String methodName) {
methodName = methodName.substring(3);
return methodName.substring(0, 1).toLowerCase() + methodName.substring(1);
}
/**
* list
*
* @return
*/
private List parseList(JSONObject json, String propertyName, Class type) {
try {
JSONArray jsonArray = json.getJSONArray(propertyName);
List result = type.isInterface() ? new ArrayList() : (List) type.newInstance();
Object param;
for (int i = 0; i < jsonArray.size(); i++) {
try {
param = parse(jsonArray.getJSONObject(i), typeClass.get(propertyName));
if (null == param)
param = jsonArray.get(i);
result.add(param);
} catch (JSONException e) {
result.add(jsonArray.get(i));
}
}
return result;
} catch (Exception e) {
return null;
}
}
/**
* map
*
* @param json
* @param propertyName
* @param type
* @return
*/
private Map parseMap(JSONObject json, String propertyName, Class type) {
try {
Map map = type.isInterface() ? new HashMap() : (Map) type.newInstance();
JSONObject jsonObj = json.getJSONObject(propertyName);
Iterator<String> keys = jsonObj.keys();
String key;
Object param;
while (keys.hasNext()) {
key = keys.next();
try {
param = parse(jsonObj.getJSONObject(key), typeClass.get(propertyName));
if (null != param)
param = jsonObj.get(key);
map.put(key, param);
} catch (JSONException e) {
map.put(key, jsonObj.get(key));
}
}
return map;
} catch (Exception e) {
return null;
}
}
/**
* JavaBean
*
* @param json
* @param propertyName
* @return
*/
private Object parseObject(JSONObject json, String propertyName) {
try {
if (null == typeClass || typeClass.get(propertyName) == null)
return null;
JSONObject jsonObject = json.getJSONObject(propertyName);
return parse(jsonObject, typeClass.get(propertyName));
} catch (Exception e) {
return null;
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.