반응형
JSON이 JSONObject인지 JSONArray인지 확인
서버에서 JSON 배열 또는 배열을 수신하지만 어느 것이나 마찬가지입니다. JSON으로 작업해야하지만 그렇게해야 객체인지 확인합니다.
Android로 작업하고 있습니다.
아무도없는 좋은 방법이 있습니까?
나는 더 나은 결정 방법을 찾았다.
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
토크 나이 저는 더 많은 유형을 리턴 할 수 있습니다. http://developer.android.com/reference/org/json/JSONTokener.html#nextValue ()
이를 수행 할 수있는 몇 가지 방법이 있습니다.
- 유효한 JSON에서 허용되는 공백을 자른 후의 첫 번째 위치에서 문자를 확인할 수 있습니다. 을 그것이이면
{
처리하고 있고JSONObject
이면을[
처리하고있는을 구석으로JSONArray
입니다. - JSON (
Object
)을 다루는 경우instanceof
검사를 수행 할 수 있습니다 .yourObject instanceof JSONObject
. yourObject가 JSONObject 인 경우 true를 반환합니다. JSONArray도 동일하게 적용됩니다.
이것은 Android에서 사용하는 간단한 솔루션입니다.
JSONObject json = new JSONObject(jsonString);
if (json.has("data")) {
JSONObject dataObject = json.optJSONObject("data");
if (dataObject != null) {
//Do things with object.
} else {
JSONArray array = json.optJSONArray("data");
//Do things with array
}
} else {
// Do nothing or throw exception if "data" is a mandatory field
}
다른 방법을 제시 :
if(server_response.trim().charAt(0) == '[') {
Log.e("Response is : " , "JSONArray");
} else if(server_response.trim().charAt(0) == '{') {
Log.e("Response is : " , "JSONObject");
}
다음 server_response
은 서버에서 오는 응답입니다.
내 접근 방식은 완전히 제거 될 것입니다. 어쩌면 누군가가 유용하다고 생각할 수도 있습니다 ...
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SimpleJSONObject extends JSONObject {
private static final String FIELDNAME_NAME_VALUE_PAIRS = "nameValuePairs";
public SimpleJSONObject(String string) throws JSONException {
super(string);
}
public SimpleJSONObject(JSONObject jsonObject) throws JSONException {
super(jsonObject.toString());
}
@Override
public JSONObject getJSONObject(String name) throws JSONException {
final JSONObject jsonObject = super.getJSONObject(name);
return new SimpleJSONObject(jsonObject.toString());
}
@Override
public JSONArray getJSONArray(String name) throws JSONException {
JSONArray jsonArray = null;
try {
final Map<String, Object> map = this.getKeyValueMap();
final Object value = map.get(name);
jsonArray = this.evaluateJSONArray(name, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonArray;
}
private JSONArray evaluateJSONArray(String name, final Object value) throws JSONException {
JSONArray jsonArray = null;
if (value instanceof JSONArray) {
jsonArray = this.castToJSONArray(value);
} else if (value instanceof JSONObject) {
jsonArray = this.createCollectionWithOneElement(value);
} else {
jsonArray = super.getJSONArray(name);
}
return jsonArray;
}
private JSONArray createCollectionWithOneElement(final Object value) {
final Collection<Object> collection = new ArrayList<Object>();
collection.add(value);
return (JSONArray) new JSONArray(collection);
}
private JSONArray castToJSONArray(final Object value) {
return (JSONArray) value;
}
private Map<String, Object> getKeyValueMap() throws NoSuchFieldException, IllegalAccessException {
final Field declaredField = JSONObject.class.getDeclaredField(FIELDNAME_NAME_VALUE_PAIRS);
declaredField.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<String, Object> map = (Map<String, Object>) declaredField.get(this);
return map;
}
}
그리고이 행동을 영원히 제거하십시오 ...
...
JSONObject simpleJSONObject = new SimpleJSONObject(jsonObject);
...
수행하는 것보다 기본적인 방법은 다음과 가변합니다.
JsonArray
존재로 목록입니다
JsonObject
내장으로 지도입니다
if (object instanceof Map){
JSONObject jsonObject = new JSONObject();
jsonObject.putAll((Map)object);
...
...
}
else if (object instanceof List){
JSONArray jsonArray = new JSONArray();
jsonArray.addAll((List)object);
...
...
}
대신에
Object.getClass (). getName ()
JavaScript 에서이 문제를 해결하는 사람들을 위해 다음이 나를 위해 일했습니다 (얼마나 확실하게 확실하지).
if(object.length != undefined) {
console.log('Array found. Length is : ' + object.length);
} else {
console.log('Object found.');
}
참고 URL : https://stackoverflow.com/questions/6118708/determine-whether-json-is-a-jsonobject-or-jsonarray
반응형
'IT' 카테고리의 다른 글
String.format에서 배열 변수를 계속 하시겠습니까? (0) | 2020.07.10 |
---|---|
Internet Explorer 8 개발자 도구가 표시되지 않음 (0) | 2020.07.10 |
다른 작업 공간에서 Eclipse 구성을 공유하는 방법 (0) | 2020.07.10 |
phpMyAdmin 3.2.4를 사용하여보기를 편집해야합니까? (0) | 2020.07.10 |
LINQ to Entities에서는 매개 변수가없는 생성자와 이니셜 라이저 만 지원됩니다. (0) | 2020.07.10 |