如何存储JSON的信息

时间:2013-09-17 11:06:59

标签: android json

我正在检索JSON数据并将其存储在数组中以供使用。

我通过以下方式获取json数据: -

Uri uri = new Uri.Builder().scheme("http").authority().path().build();
     System.out.println("uri of category is : -"+uri);
     URI u = new URI(uri.toString());

     HttpClient httpclient = new DefaultHttpClient();
     HttpGet httpget = new HttpGet(u);
     HttpResponse response = httpclient.execute(httpget);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();

     BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
     sb = new StringBuilder();
     sb.append(reader.readLine() + "\n");
     String line="0";
     while ((line = reader.readLine()) != null) {
              sb.append(line + "\n");
     }
     is.close();
     result=sb.toString(); 

但是我的json是其他类型的。所以我很困惑如何在我的arraylist中获取和存储。

{
employee: [
{
name: "ajay",
id: 1,
},
{
name: "rajiv",
id: 2,

}
],
address: [ 
{
city: "bombay",
pin: 114141 
}
]
}

我知道有第一个JSONObject并且有两个jsonarray。但我怎么能回头呢。

3 个答案:

答案 0 :(得分:1)

JSONArray jsonArray = jObject.getJSONArray("employee");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                modelJSon.setname(jsonObject.getString("name"));
                modelJSon.setid(jsonObject.getString("id"));
                modelList.add(modelJSon);
                modelJSon = new ModelBroker();
            }

JSONArray jsonArray = jObject.getJSONArray("address");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    modelJSon.setcity(jsonObject.getString("city"));
                    modelJSon.setpin(jsonObject.getString("pin"));
                    modelList.add(modelJSon);
                    modelJSon = new ModelBroker();
                }

答案 1 :(得分:0)

JSONObject json = new JSONObject(String jsonString);
JSONArray employeesArray = json.getJSONArray("employee");

final int arrayLength = employeesArray.length();
  for (int i = 0; i< arrayLength; i++) {
    JSONObject employeeJson = array.getJSONObject(i);
    // parse employee JSON and add it to your ArrayList
  }

同样使用其他阵列。

答案 2 :(得分:0)

您可以使用此

JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("employee");
JSONObject jo;
for(int i=0;i<jArray.length();i++){
    jo = jArray.getJSONObject(i);
    Log.d("name", jo.getString("name"));
    Log.d("id", jo.getString("id"));
}
jArray = jObject.getJSONArray("address");
for(int i=0;i<jArray.length();i++){
    jo = jArray.getJSONObject(i);
    Log.d("city", jo.getString("city"));
    Log.d("pin", jo.getString("pin"));
}