如何使用Gson()fromJson解析使用动态文件

时间:2016-09-22 20:18:14

标签: android gson

如何使用Gson加载动态json文件....例如:

ChatItem item = new Gson()。fromJson(Helper.loadJSONFromAsset(getApplicationContext(),“http://sample.com/a/chat_message.json”),ChatItem.class);

protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
name = getIntent().getStringExtra(Constant.NAME);
userID = Preference.getPrefString(getApplicationContext(), Constant.USER_ID);
chatUserID = getIntent().getStringExtra(Constant.CHAT_USER_ID);
loadData();
}

private void loadData() {
ChatItem item = new Gson().fromJson(Helper.loadJSONFromAsset(getApplicationContext(), "chat_message.json"), ChatItem.class);

List<ChatItem.Result> chatList;
    if (item.getStatus().equalsIgnoreCase(Constant.SUCCESS)) {
        chatList = item.getResult();
        list = new ArrayList<>();
        if (chatList.size() > 0) {
            for (ChatItem.Result result : chatList) {
                ChatMessage message = new ChatMessage();
                if (result.getId().equalsIgnoreCase(pingMe_id))
                    message.setLeft(false);
                else
                    message.setLeft(true);
                message.setMessage(result.getChat());
                list.add(message);
            }
            adapter = new ChatMessageAdapter(getApplicationContext(), list);
            listView.setAdapter(adapter);
        }
    }
}

0 个答案:

没有答案