2012-05-16 4 views
0

항상있을 수있는 유일한 방법은 messagesByDate obj입니다. "15 May 2012"와 같은 이름의 배열 및 개체는 해당 날짜에 대한 메시지가 있거나없는 기반 서버 (제어 없음)에 의해 생성됩니다.Android :이 json 응답을 어떻게 분석해야합니까?

다른 날짜가 번호가 매겨진 다른 개체를 포함하는 개체 인 반면, 표시된 첫 번째 날짜는 배열입니다.

질문 1 : 어떤 날짜를 알지 못하면 어떻게 파싱합니까?

질문 2 : 일부 메시지는 개체 대신 배열에 있습니다. 어떻게 하나의 ArrayList에 모두 함께 넣을 수 있습니까? 오히려 그것의 배열에서 배열이 항상 거기에 없었기 때문에 또는 아닙니다.

나는 내 마지막 머리까지

감사 해요로 어떤 도움을 주시면 감사하겠습니다하시기 바랍니다.

{ 
"messagesByDate":{ 
    "15 May 2012":[ 
    { 
     "id":"1383483367", 
     "conversation_id":"274618561", 
     "user_id":"4318264", 
     "message":"ok will do", 
     "date_sent":"1337133515", 
     "date_sent_ago":"7 mins ago" 
    }, 
    { 
     "id":"1380222533", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"ok well hmu", 
     "date_sent":"1337085122", 
     "date_sent_ago":"13 hrs ago" 
    }, 
    { 
     "id":"1380172978", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"superhead", 
     "date_sent":"1337083910", 
     "date_sent_ago":"13 hrs ago" 
    }, 
    { 
     "id":"1380130860", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"you ready B", 
     "date_sent":"1337082797", 
     "date_sent_ago":"14 hrs ago" 
    }, 
    { 
     "id":"1378841432", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"hit my cell tho", 
     "date_sent":"1337054524", 
     "date_sent_ago":"22 hrs ago" 
    }, 
    { 
     "id":"1378836763", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"whats up baby", 
     "date_sent":"1337054475", 
     "date_sent_ago":"22 hrs ago" 
    } 
    ], 
    "12 May 2012":{ 
    "6":{ 
     "id":"1362948558", 
     "conversation_id":"274618561", 
     "user_id":"4318264", 
     "message":"ok ima text u", 
     "date_sent":"1336819668", 
     "date_sent_ago":"3 days ago" 
    } 
    }, 
    "11 May 2012":{ 
    "7":{ 
     "id":"1361356267", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"yea thats cool", 
     "date_sent":"1336790738", 
     "date_sent_ago":"3 days ago" 
    }, 
    "8":{ 
     "id":"1357783913", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"sorry im here. would u like to exchange numebers instead?", 
     "date_sent":"1336722533", 
     "date_sent_ago":"4 days ago" 
    }, 
    "9":{ 
     "id":"1357759262", 
     "conversation_id":"274618561", 
     "user_id":"5159567", 
     "message":"hello?", 
     "date_sent":"1336721851", 
     "date_sent_ago":"4 days ago" 
    } 
    } 
    } 
} 

대답은 그렇다고-좀

JSONObject dateHolder = r.getJSONObject("messagesByDate"); 
    Iterator holderItr = dateHolder.keys(); 


    while(holderItr.hasNext()){ 


     String thisdate = holderItr.next().toString(); 
     Object date = dateHolder.get(thisdate); 


     if (date instanceof JSONArray) { 
      System.out.println(thisdate+" is an ARRAY."); 
      JSONArray jarray = (JSONArray) date; 
      for(int x=0;x<jarray.length();x++){ 
       String msgId = jarray.getJSONObject(x).getString("id"); 
       String msgConvoId = jarray.getJSONObject(x).getString("conversation_id"); 
       String msgUserId = jarray.getJSONObject(x).getString("user_id"); 
       String msgBody = jarray.getJSONObject(x).getString("message"); 
       String msgDateSent = jarray.getJSONObject(x).getString("date_sent"); 
       String msgDateSentAgo = jarray.getJSONObject(x).getString("date_sent_ago"); 
       HashMap<String,String> temp = new HashMap<String,String>(); 
       temp.put("msgId",msgId); 
       temp.put("msgUserId", msgUserId); 
       temp.put("msgBody", msgBody); 
       temp.put("msgDateSent", msgDateSent); 
       temp.put("msgDateSentAgo", msgDateSentAgo); 
       messages.add(temp); 

      } 
     } else { 
      System.out.println(thisdate+" is an OBJECT."); 
      JSONObject jobj = (JSONObject) date; 
      Iterator insideDate = jobj.keys(); 
      while(insideDate.hasNext()){ 
       String number = insideDate.next().toString(); 
       System.out.println(number); 
       String msgId = jobj.getJSONObject(number).getString("id"); 
       String msgConvoId = jobj.getJSONObject(number).getString("conversation_id"); 

       String msgUserId =jobj.getJSONObject(number).getString("user_id"); 

       String msgBody = jobj.getJSONObject(number).getString("message"); 

       String msgDateSent = jobj.getJSONObject(number).getString("date_sent"); 

       String msgDateSentAgo = jobj.getJSONObject(number).getString("date_sent_ago"); 
       HashMap<String,String> temp = new HashMap<String,String>(); 
       temp.put("msgId",msgId); 
       temp.put("msgUserId", msgUserId); 
       temp.put("msgBody", msgBody); 
       temp.put("msgDateSent", msgDateSent); 
       temp.put("msgDateSentAgo", msgDateSentAgo); 
       messages.add(temp); 

      } 
     } 
    } 

이 내게는 HashMap에있는 모든 메시지를 제공하고 ArrayList에에 추가 내가 원하는 같은 메시지라고하지만 날짜별로 순서는 부족합니다. json은 날짜순으로 나열됩니다 ... json 읽기를 지시하는 방법이 있다면 누구든지 알 수 있습니까? 또는 WHILE 및 FOR 루프 순서가 잘못 되었습니까? 해시 맵을 키별로 정렬 할 수 있습니까? 나는 구글거야 ...

답변

0
JSONObject json = service.getJunk(); 
JSONObject msgJson = json.getJSONObject("messagesByDate"); 
for(Iterator it = msgJson.keys(); it.hasNext();) { 
    Object obj = msgJson.get((String)it.next()); 
    if(obj instanceof JSONObject) { 
     JSONObject jobj = (JSONObject)obj; 
     // process json object 
    } else { 
     JSONArray arry = (JSONArray)obj; 
     // process array 
    } 
} 
+0

Eclipse는 for 문이 msgJson.keys()에 대해 변수 또는 iterable 인스턴스를 사용해야 함을 알립니다. – TonyCruze

+0

Java에서 이전 스타일 반복을 사용하도록 변환하는 것은 꽤 쉽습니다. 나는 이번에 코드를 업데이트했다. 내 머리 꼭대기에서이 작업을하고 있다는 것을 명심하십시오. 나는 이것을 테스트하지 않을 것이므로 이렇게 간단한 구문 변경은 독자가 독자적으로 할 수 있어야하는 것입니다. – chubbsondubs

+0

예전에 FOR 문 대신 Iterator next()와 hasNext()를 사용하기 시작했으며 꽤 가까워졌습니다. 하지만 두 가지를 결합하지 않도록 노력하겠습니다. 내가 놓친 중요한 부분은 단순히 '인스턴스'인지 테스트하는 것입니다. 나는이 예제를 살펴보고 테스트 해보고 작동하도록 할 수 있는지 알아 봅니다. 너무 고마워. – TonyCruze

1

먼저이 같은 클래스 생성 :

if(Manager.isOnline(this)) // Check Internet connection and if you find it then 
      new MyAsyncTask().execute(); 

:

import java.util.LinkedList; 
import android.util.Log; 

public class Message{ 

    private LinkedList<String> id    = new LinkedList<String>(); 
    private LinkedList<String> conversation_id = new LinkedList<String>(); 
    private LinkedList<String> user_id  = new LinkedList<String>(); 
    private LinkedList<String> message  = new LinkedList<String>(); 
    private LinkedList<String> date_sent  = new LinkedList<String>(); 
    private LinkedList<String> date_sent_ago = new LinkedList<String>(); 

    public LinkedList<String> getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id.add(id); 
    } 

. 
. 
. 
    // For checking response after you get info from server 
    public void printContent() { 
     for(String str : id) 
      Log.i("Id>>>", str); 
. 
. 
. 
    } 

} 

그런 다음이 코드를 추가) (에서 onCreate에 서버를 호출 할 필요를 이제이 클래스를 추가해야합니다.

public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> { 

     @Override 
     protected void onPreExecute() { 
      Log.i(TAG, "MyAsyncTask is about to start..."); 
      showProgressBar(); 
     } 


     @Override 
     protected Boolean doInBackground(Void... params) { 
      boolean status = false; 

      // Get News items in json format 
      msg = getMessageItems(); // msg is an instance of Message class define it as global variable. 
      msg.printContent(); // Check result in logcat 

      if(msg != null) 
       status = true; 

      return status; 
     } 


     @Override 
     protected void onPostExecute(Boolean result) { 
      Log.i(TAG, "MyAsyncTask finished its task. Data returned to caller."); 

      if(result) 
       displayData(); 

      hideProgressBar(); 
     } 
    } 

여기에 추가해야합니다. 우리는 서버에 연결하고 Json 데이터를 가져 와서 구문 분석합니다.

private Menu getMenuItems() { 
    Message mMessage = new Message(); 
    String response = null; 
    String connection = **YOUR_URL**; 

    try { 
     URL url = new URL(connection); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

     int responseCode = conn.getResponseCode(); 
     Log.i(TAG, "Try to open: " + connection); 
     Log.i(TAG, "Response code is: " + responseCode); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      if (in != null) { 
       StringBuilder strBuilder = new StringBuilder(); 
       // Read character by character    
       int ch = 0; 
       while ((ch = in.read()) != -1) 
        strBuilder.append((char) ch); 

       // get returned message and show it 
       response = strBuilder.toString(); 
       Log.i("JSON returned by server:", response); 

       JSONObject jObject = new JSONObject(response); 
       JSONArray contestantObjects = jObject.getJSONArray("**messagesByDate**"); 
       for(int i=0; i<contestantObjects.length(); i++){ 
        mMessage .setId(contestantObjects.getJSONObject(i).getString("id").toString()); 
// Repeat this to get all of other items 
       } 
      } 

      in.close(); 

     } else 
      Log.e(TAG, "Couldn't open connection in getMenuItems()"); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    return mMessage; 
} 

이제 각 항목이 목록이라는 개체가 있습니다. 당신은 당신이 원하는 어떤 것을 디스플레이 방법으로 할 수 있습니다. 어댑터에 객체로 전달하여 데이터를 표시 할 수 있습니다.

private void displayData() { 
     messageAdapter.setData(msg); 
     listView.setAdapter(messageAdapter); 
    } 

희망이 샘플 코드는 도움이됩니다.

+0

이 샘플은 내가 원하는 것 (어댑터 용 데이터 목록)과 함께 진행중입니다.그러나이 샘플의 모든 부분을 머리 속에 감싸는 데는 시간이 걸릴 것입니다. 당면한 문제 이외의 문제가 더 많이 발생할 수도 있습니다. 하지만 나는 그것을 시도해 보려고한다. 나는 asyctasks로 놀고 싶어한다. 다시 한번 감사드립니다. – TonyCruze

관련 문제