0

唯一可以保证始终存在的是 messagesByDate obj。名为“2012 年 5 月 15 日”的数组和对象是由服务器(无控制)根据该日期是否存在消息而生成的。

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

问题 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 循环是否有问题?我可以按键对哈希图进行排序吗?我会用谷歌搜索...

4

2 回答 2

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);
    }
于 2012-05-16T04:03:34.603 回答
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
    }
}
于 2012-05-16T03:45:03.877 回答