如何在Android中正确解析所有JSON值

时间:2013-10-29 15:02:44

标签: java android arrays json

首先:Android代码

public class MachineController extends AsyncTask<String, String,List<Machine>> {

private static String REST_URL = "...";
List<Machine> machines;


@Override
protected List<Machine> doInBackground(String... params) {
    machines = new ArrayList<Machine>();


    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(REST_URL);
    httpGet.addHeader("accept", "application/json");

    HttpResponse response;
    try {
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null)
                sb.append(line + "n");

            String result = sb.toString();


            Gson gson = new Gson();
            JsonReader jsonReader = new JsonReader(new StringReader(result));
            jsonReader.setLenient(true);

            JsonParser parser = new JsonParser();
            JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();

            for (JsonElement obj : jsonArray) {
                Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
                machines.add(machine);
                machines.get(0);

            }

            instream.close();

        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return machines;
}

}

以下是JSON文件的一些代码

 [ 
{ "mobileMachine": 
{ "condition":"VERY_GOOD",
 "document":"", . . .
 "mobileCategory": {   "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
 "mobileCategoryEng":"Bookletmaker",
 "mobileCategoryGer":"Broschuerenfertigung" }, 
"modelYear":2006, 
Abmessungen: 665x810mm " } }

{ "mobileMachine": 
{
     "condition":"VERY_GOOD"," ...... } } ]

有时候里面有一个mobileCategory。列表中的mobileCategoryGer和mobileCategoryEng始终为null。

我无法编辑JSON文件!我只想从Json文件中获取mobileCategoryGer和mobileCategoryEng的值。其余工作正常。我希望你明白并且可以帮我解析它。

(对不起我的英文)

2 个答案:

答案 0 :(得分:0)

你走了。

    Type listType = new TypeToken<List<Machine>>() {}.getType();
    ArrayList<Result> results = gson.fromJson(result, listType);

以下是完整修改后的代码:

  public class MachineController extends AsyncTask<String, String,List<Machine>> {

     private static String REST_URL = "...";
     List<Machine> machines;


     @Override
   protected List<Machine> doInBackground(String... params) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(REST_URL);
    httpGet.addHeader("accept", "application/json");

   HttpResponse response;
   try {
    response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null)
            sb.append(line + "n");

        String result = sb.toString();


        Gson gson = new Gson();

       Type listType = new TypeToken<List<Machine>>() {}.getType();
       machines= gson.fromJson(result, listType);

        instream.close();

    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
return machines;

}

答案 1 :(得分:0)

您可以使用has()方法检查密钥是否具有密钥。您还可以使用optJSONObject()获取可选值,并检查它是否为空。

JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
    doSomething(jsonArray);
} catch (JSONException e) {  
   Log.wtf("Terrible Failure", e);
}


private void doSomething(JsonArray jsonArray) throws JSONException{
        for (int i=0; i<jsonArray.length(); i++){
            JSONObject obj = jsonArray.getJSONObject(i);
            JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
            if(mobileCategory !=null){
                if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
                    String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
                    String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
                }
            }
        }
    }