如何从JSON响应创建对象?

时间:2015-12-08 13:15:22

标签: java json parsing object messages

美好的一天!我有一个从服务器获取JSON响应的应用程序。 我的回答如下:



{
  "in_read": 414638,
  "count": 156,
  "out_read": 414637,
  "items": [
    {
      "date": 1449573812,
      "from_id": 1234,
      "read_state": 1,
      "user_id": 1234,
      "fwd_messages": [
        {
          "date": 1449573809,
          "user_id": 1234,
          "fwd_messages": [
            {
              "date": 1449573760,
              "user_id": 1234,
              "fwd_messages": [
                {
                  "date": 1449573729,
                  "user_id": 1234,
                  "body": "msg31"
                },
                {
                  "date": 1449573749,
                  "user_id": 1234,
                  "fwd_messages": [
                    {
                      "date": 1449573739,
                      "user_id": 1234,
                      "body": "msg321"
                    },
                    {
                      "date": 1449573741,
                      "user_id": 1234,
                      "body": "smg322"
                    }
                  ],
                  "body": "msg32"
                }
              ],
              "body": "msg3"
            }
          ],
          "body": "msg2"
        }
      ],
      "id": 414599,
      "body": "msg1",
      "out": 0
    }
  ]
}




每次转发邮件的数量都不同。所以,我想将这些消息存储到一个对象中。我想我应该创建一个消息对象,它可以包含转发消息列表,转发消息可以包含其他消息。我的消息对象是:

public class Message implements Serializable {
public long date = 0;
public long fromId;
public boolean readState;
public int userId;
public String body;
public ArrayList<FwdMessage> fwdMessages;

public Message(long date, long fromId, String body) {
    this.date = date;
    this.fromId = fromId;
    this.body = body;
}}

我还有我的Forwarded消息对象:

public class FwdMessage implements Serializable {
public long date;
public long userId;
public String body;
public List<FwdMessage> fwdMessages;

public FwdMessage(String body) {
    this.body = body;
}

public void addFwd(FwdMessage fwdMessage) {
    this.fwdMessages.add(fwdMessage);
}}

当然,由于这种方法,我可以将所有消息都放在一起:

&#13;
&#13;
static int m = 0;

    public static void fwd(JSONObject o) {
        System.out.println(o.getString("body"));
        if(o.has("fwd_messages")) {
            m++;
            JSONArray array = o.getJSONArray("fwd_messages");
            for (int i = 0; i < array.length(); i++) {
                for (int j = 0; j < m; j++) {
                    System.out.print("\t");
                }
                fwd(array.getJSONObject(i));
            }
            m--;
        }
    }
&#13;
&#13;
&#13;

但是如何将所有消息放在一起,因为我希望它们应该按层次顺序排列(例如,第1个fwd_msgs还有另外两个fwd_messages,它们有另一个fwd_messages)?请帮助我,抱歉我的英语:)

0 个答案:

没有答案