com.swisscom.safeconnect.json.ResourceJsonParser.java Source code

Java tutorial

Introduction

Here is the source code for com.swisscom.safeconnect.json.ResourceJsonParser.java

Source

/*
 Swisscom Safe Connect
 Copyright (C) 2014 Swisscom
    
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.swisscom.safeconnect.json;

import android.content.Context;
import android.text.Html;
import android.util.Log;

import com.swisscom.safeconnect.BuildConfig;
import com.swisscom.safeconnect.utils.Config;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

public class ResourceJsonParser extends JsonParser<ResourceJsonParser.Elem> {
    public static class Elem implements Serializable {
        private static final long serialVersionUID = -8003667116915415687L;

        public CharSequence title;
        public CharSequence content;
    }

    private List<Elem> result;

    public ResourceJsonParser(Context c, int resId) {
        result = new LinkedList<Elem>();

        InputStream is = c.getResources().openRawResource(resId);
        parseJson(toJsonString(is));
    }

    @Override
    protected void parseJson(String json) {
        try {
            JSONArray jsonArr = new JSONArray(json);

            for (int i = 0; i < jsonArr.length(); i++) {
                JSONObject jsonElem = jsonArr.getJSONObject(i);

                Elem elem = new Elem();
                elem.content = Html.fromHtml(jsonElem.getString("content"));
                elem.title = jsonElem.getString("title");

                result.add(elem);
            }
        } catch (JSONException e) {
            if (BuildConfig.DEBUG)
                Log.e(Config.TAG, "Json error: " + e.getMessage(), e);
        }
    }

    @Override
    public Elem getResult() {
        return null;
    }

    @Override
    public List<Elem> getListResult() {
        return result;
    }
}