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

Java 如何在Android中正确解析所有JSON值,java,android,arrays,json,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

首先是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;
}
有时里面有一个移动分类。mobileCategoryGer和mobileCategoryEng在列表中始终为空

我无法编辑JSON文件!我只需要Json文件中mobileCategoryGer和mobileCategoryEng的值。其余的工作正常。我希望你能理解并帮助我正确解析它

(对不起我的英语)

给你

    Type listType = new TypeToken<List<Machine>>() {}.getType();
    ArrayList<Result> results = gson.fromJson(result, listType);
Type listType=new-TypeToken(){}.getType();
ArrayList results=gson.fromJson(结果,列表类型);
以下是您的完整修改代码:

  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;
公共类MachineController扩展异步任务{
私有静态字符串REST_URL=“…”;
列出机器清单;
@凌驾
受保护列表doInBackground(字符串…参数){
HttpClient HttpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(REST\u URL);
addHeader(“接受”、“应用程序/json”);
HttpResponse响应;
试一试{
response=httpClient.execute(httpGet);
HttpEntity=response.getEntity();
如果(实体!=null){
InputStream instream=entity.getContent();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(instream));
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null)
sb.附加(第+行“n”);
字符串结果=sb.toString();
Gson Gson=新的Gson();
类型listType=newTypeToken(){}.getType();
machines=gson.fromJson(结果,列表类型);
流内关闭();
}
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回机器;

}

您可以使用方法检查它是否具有密钥。您还可以使用方法获取可选值并检查它是否不为null

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");
                }
            }
        }
    }
JsonArray-JsonArray=parser.parse(jsonReader.getAsJsonArray();
试一试{
剂量测定法(jsonArray);
}捕获(JSONException e){
Log.wtf(“严重故障”,e);
}
私有void doSomething(JsonArray JsonArray)抛出JSONException{

对于(int i=0;iIs是否正确?如果我粘贴了代码,应用程序崩溃…我想将mobileCategoryGer和mobileCategoryEng也添加到机器列表中。将两者定义为机器类中的实例变量,你能给我一个代码示例(基于我的代码)?:+)
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");
                }
            }
        }
    }