将JSON解析为对象并在分层的微调器中显示它?

时间:2014-08-04 19:37:10

标签: java android json

我正在编写一个从Web主机访问JSON文件的应用程序。这些文件包含有关不同位置,设施等的信息。我试图提出一种方法,使我们能够快速轻松地解析信息并将其显示在分层旋转器中以微调信息。

在网站上我们使用树视图,所以这是我的移动解决方案。

You can find an example of the JSON output here.

我真的不知道一种解决所有问题的好方法,而且我现在所做的事情似乎有些混乱,这是我目前所做的一个例子:

private void generatePlants(String json) {
    try {
        JSONObject jObject = new JSONObject(json);
        String aJsonString = jObject.getString("company");
        jObject = new JSONObject(aJsonString);
        JSONArray jArray = jObject.getJSONArray("plant");

        plants = new String[jArray.length()+1];
        plants[0] = "";

        for (int i = 0; i < jArray.length(); i++) {
                JSONObject unitObject = jArray.getJSONObject(i);
                plants[i+1] = unitObject.getString("plantLocation");
        }

        Spinner spinner = (Spinner)getActivity().findViewById(R.id.spnLocation);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_spinner_item, plants);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    } catch (Exception e) {
        Log.e("SolidCM", "exception", e);
    }
}

private void generateUnits(String json, int plant) {
    try {
        JSONObject jObject = new JSONObject(json);
        String aJsonString = jObject.getString("company");
        jObject = new JSONObject(aJsonString);
        JSONArray jArray = jObject.getJSONArray("plant");
        aJsonString = jArray.getString(plant);
        Log.d("DEBUG",aJsonString);
        jObject = new JSONObject(aJsonString);
        jArray = jObject.getJSONArray("unit");

        units = new String[jArray.length()+1];
        units[0] = "";

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject unitObject = jArray.getJSONObject(i);
            units[i+1] = unitObject.getString("unitName");
        }

        Spinner spinner = (Spinner)getActivity().findViewById(R.id.spnView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_spinner_item, units);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    } catch (Exception e) {
        Log.e("SolidCM", "exception", e);
    }
}

private String getJson() {
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://jdhpro.com/downloads/testData.json");

    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        result = sb.toString();
    } catch (Exception e) {
        Log.e("SolidCM", "exception", e);
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        return result;
    }
}

1 个答案:

答案 0 :(得分:0)

我个人的方法是将每个JSON对象表示为Java类。一种流行的方式是使用GSON,但我从未使用它,也无法就此进一步提出建议。

但是,你可以自己做。首先使用“公司”JSON对象从顶部开始工作,该对象将由以下Java类表示...

public class Company {
    private String mCompanyId;
    private String mCompanyName;

    // Fields for address, phone, email etc

    private ArrayList<Plant> mPlantList;

    // Getters and setters here

    public Company (String jsonString) {
        // The jsonString will be the value (object) of the
        // "company" : {...} JSON name/value pair.
        // Parse the JSON for companyId, companyName, address etc
        // until you get to the "plant" : [...]" JSON array. Iterate
        // over the array creating a new Plant Java object passing in
        // the JSON object for each plant
    }
}

现在是“植物”JSON对象......

public class Plant {
    private String mPlantId;
    private String mPlantLocation;
    private ArrayList<Unit> mUnitList;

    // Getters and setters here 

    public Plant (String jsonString) {
        // Do the same as the Company constructor - parse the JSON
        // for plantId and plantLocation then when you get to the
        // "unit" : [...] JSON array, iterate over it create new
        // instances of the Unit Java class passing in the JSON for
        // each JSON unit object
    }
}

好的,所以我已停止参加公司和工厂课程,但你可以希望看到这种模式。为Company,Plant,Unit,EquipType,Equip创建一个Java类,并让每个类解析自己的JSON。

现在来到Spinner部分。 ArrayAdapter可以与任意对象一起使用。即使您只使用一个TextView作为Spinner项视图,也可以简单地覆盖类的toString()方法,以允许ArrayAdapter绑定到TextViews 1}}。

使用上述公司Java类的示例...

public class Company {
    ...
    public String toString() {
        return mCompanyName;
    }
}

ArrayList<Company>示例(假设您有多家公司)......

ArrayList<Company> companyList = new ArrayList<Company>;

// Parse your JSON and add the companies to the ArrayList

ArrayAdapter<Company> adapter = new ArrayAdapter<Company>(getActivity(),
            android.R.layout.simple_spinner_item, companyList);