Android:我如何解析这个混合的json响应

时间:2012-05-16 03:35:17

标签: android arrays json parsing object

唯一保证永远存在的是messagesByDate obj。 名为“15 MAY 2012”的数组和对象由服务器(无控制)生成,基于此日期是否存在消息。

如果您注意到表示的第一个日期是数组,而其他日期是包含已编号的其他对象的对象。

问题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"
     }
     }
   }
}

答案SORTA-KINDA

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中的所有消息,并将它添加到一个名为messages的ArrayList,就像我想要的那样,但它按日期排序。 json按日期列出...任何人都知道是否有办法指导json阅读?或者我的WHILE和FOR循环乱序?我可以用密钥对哈希图进行排序吗?我会谷歌...

2 个答案:

答案 0 :(得分:1)

首先创建一个这样的类:

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()中调用server添加这段代码:

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

现在,您应该添加此类:

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);
    }

希望此示例代码可以帮助您。

答案 1 :(得分: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
    }
}