2017-01-11 1 views
1

나는 다음과 같은 JSON 응답을 받고 있어요 처리 방법 : 객체의 "데이터"가끔은으로 배열되어개조 JSON 동적

"status": true, 
"data":{ 
    //Some data 
} 

을 : 데이터의 응답을 확인하는 방법

"status": true, 
"data":[ 
    //Some data 
] 

동적으로 객체 또는 배열입니까? 사전에

@SerializedName("data") 
ArrayList<DataDetail> dataList; 

감사 : * 나는대로 배열 분석 개조

내 개조를 사용하고 있습니다!

+0

가능한 복제본은 [JSON이 JSONObject인지 JSONArray인지 결정]입니다 (http://stackoverflow.com/questions/6118708/determine-whether-json-is-a-jsonobject-or-jsonarray). –

+0

나는이 모든 것을 관리 할 수 ​​없다고 생각합니다. 당신의 개장을 위해 백그라운드에서 파슨스 (json parsing)와 관련된 모든 일이 일어나기 때문입니다. 그래서 instanceof를 확인합니다. 개조 공사 구조를 변경해야합니다. –

+0

네, 정확히 똑같은 문제에 직면하고 있습니다. @Ready Android –

답변

1

:이 JsonElement을 변환하려면 지금

@SerializedName("data") 
private JsonElement data; 

귀하의 요구 사항에 따라 귀하의 해당 모델을 아래 코드를 사용할 수 있습니다 :

if(data instanceOf JsonObject){ 
    YourModelForData object = YourDataComponentForObject(data); 
    // Do anything with Object 
} else { 
    List<YourModelForData> array = YourDataComponentForArray(data); 
    // Do anything with array 
} 

public YourModelForData YourDataComponentForObject(JsonElement data) { 
    Type type = new TypeToken<YourModelForData>() { 
    }.getType(); 
    YourModelForData item = new Gson().fromJson(data, type); 
} 

public List<YourModelForData> YourDataComponentForArray(JsonElement data) { 
     Type type = new TypeToken<List<YourModelForData>>() { 
     }.getType(); 
     List<YourModelForData> items = new Gson().fromJson(data, type); 
} 

해피 코딩 < {}>;

+0

이 메서드는 목록 만 반환하지만 개체 만 제공되면 어떻게됩니까? –

+0

내 대답을 편집했습니다. 시도해보십시오. 객체 또는 배열 검사는 instanceof를 사용하여 유지 관리해야하고 JsonElement에서 serialise 데이터 유형을 처리하게해야합니다. gson을 사용하여 getAsJsonObject 또는 getAsJsonArray를 사용하여 json을 유형 캐스팅 할 수도 있습니다. –

+0

잘 봐라!,하지만 위의 메서드를 호출 할 위치, 그리고 무엇을 반환 할 것인가? @Siraj Sumra –

2
JSONObject json; 
Object  intervention; 
JSONArray interventionJsonArray; 
JSONObject interventionObject; 

json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream  
Object intervention = json.get("intervention"); 
if (intervention instanceof JSONArray) { 
    // It's an array 
    interventionJsonArray = (JSONArray)intervention; 
} 
else if (intervention instanceof JSONObject) { 
    // It's an object 
    interventionObject = (JSONObject)intervention; 
} 
else { 
    // It's something else, like a string or number 
} 

확인이 스레드 json으로 그것이 된 JSONObject 또는 JsonArray 할 것인지, 단순히 아래와 같이 JsonElement를 사용하는 것이 알 수없는 경우 Test if it is JSONObject or JSONArray