0

SD カードに JSON オブジェクトの配列があります。

次のようなファイルの内容を取得します。

File yourFile = new File("/mnt/extSdCard/test.json");
        FileInputStream stream = new FileInputStream(yourFile);
        String jString = null;
        try {
            FileChannel fc = stream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            /* Instead of using default, pass in a decoder. */
            jString = Charset.defaultCharset().decode(bb).toString();
          }
          finally {
            stream.close();
          }

構造は次のようになります。

[{"name":"john"},{"name":"fred"},{"name":"sam"}]

それらを解析してlistViewを作成できるようにしたいと考えています。JavaScriptでは、それらをAJAXリクエストとして取得してから実行できます

var people = JSON.parse(data.responseText);

次に、配列をループします。しかし、私はJavaの完全な初心者です。これらのことを個別に実行するサンプルコードを見つけましたが、それらをすべてまとめることができません。どんな助けでも大歓迎です。

4

3 に答える 3

2

JSONObject文字列として持っている場合は、次のようなもので解析できるはずです。

JSONObject jObj = null;

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
    Log.i(TAG, "JSON Data Parsed: " + jObj.toString());
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

また、データ(あなたの例では)を配列に入れるので、次のようになります。

{"names": [{"name": "john"},{"name": "fred"},{"name": "sam"}]}

そして、オブジェクトを再度読み取るには、次のようにして配列 (または私が推測するもの) に入れることができます。

// create an empty list
ArrayList<String> l = new ArrayList<String>();
// pull the array with the key 'names'
JSONArray array = jObj.getJSONArray("names");
// loop through the new array
for(int i = 0; i < array.length(); i++){
    // pull a value from the array based on the key 'name'
    l.add(array.getJSONObject(i).getString("name"));
}

これの少なくとも一部が役立つことを願っています(または、少なくとも正しい方向にあなたを向けます)。ただし、ここにもたくさんのリソースがあります。

編集:

JSON フォーマットについて読んでください。 []は配列を{}表し、オブジェクトを表すため、オブジェクトの配列があります。そのため、フォーマットを変更することをお勧めしました。フォーマットに設定されている場合は、Mr.Me が彼の回答に投稿したものを使用するか、文字列を特殊文字で分割してそのように配列に入れます。

于 2013-05-03T16:09:28.133 に答える
0

これを試して

String[] from = new String[] {"name"};
int[] to = new int[] { R.id.name};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

try 
{
    JSONArray names = new JSONArray(jsonString);
    Log.i("MyList","Number of names " + names.length());
    for (int j = 0; j < names.length(); j++) 
    {
         JSONObject jsonObject = names.getJSONObject(j);
         HashMap<String, String> map = new HashMap<String, String>();
         map.put("name", jsonObject.getString("name"));
         fillMaps.add(map);
    }
} 
catch (Exception e) 
{
    e.printStackTrace();
}

SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
mListView.setAdapter(adapter);

これmListViewが事前定義されListViewた です。疑問がある場合は、ここで自由に共有してください。

于 2013-05-03T17:03:01.257 に答える