ParseJson.java,解析结果如果没有数组名?

时间:2021-01-09 21:19:21

This is my code:

这是我的代码:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Belal on 9/22/2015.
 */
public class ParseJSON {
    public static String[] make;
    public static String[] model;
    public static String[] sixMonthRate;

    public static final String JSON_ARRAY = "result";
    public static final String KEY_MAKE = "make";
    public static final String KEY_MODEL = "model";
    public static final String KEY_SIXMONTHRATE = "sixMonthRate";

    private JSONArray vehicle = null;

    private String json;

    public ParseJSON(String json){
        this.json = json;
    }

    protected void parseJSON(){
        JSONObject jsonObject=null;
        try {
            jsonObject = new JSONObject(json);
            vehicle = jsonObject.getJSONArray(JSON_ARRAY);

            make = new String[vehicle.length()];
            model = new String[vehicle.length()];
            sixMonthRate = new String[vehicle.length()];

            for(int i=0;i<vehicle.length();i++){
                JSONObject jo = vehicle.getJSONObject(i);
                make[i] = jo.getString(KEY_MAKE);
                model[i] = jo.getString(KEY_MODEL);
                sixMonthRate[i] = jo.getString(KEY_SIXMONTHRATE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

If I will use DVLA JSON DATABASE and there is no ARRAY name , how should I change the code to make it work?

如果我将使用DVLA JSON DATABASE并且没有ARRAY名称,我应该如何更改代码以使其工作?

Currently if I press button get the data, I have result as app closed.

目前,如果我按下按钮获取数据,我的结果是app已关闭。

I'm using this tutorial - HERE

我正在使用这个教程 - 这里

Error get

03-26 02:49:43.467 23673-23673/com.sandro.openalprsample W/System.err: org.json.JSONException: No value for result
03-26 02:49:43.467 23673-23673/com.sandro.openalprsample W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
03-26 02:49:43.467 23673-23673/com.sandro.openalprsample W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:584)
03-26 02:49:43.467 23673-23673/com.sandro.openalprsample W/System.err:     at com.sandro.openalprsample.ParseJSON.parseJSON(ParseJSON.java:42)
03-26 02:49:43.467 23673-23673/com.sandro.openalprsample W/System.err:     at com.sandro.openalprsample.DVLAresult.showJSON(DVLAresult.java:60)
03-26 02:49:43.467 23673-23673/com.sandro.openalprsample W/System.err:     at com.sandro.openalprsample.DVLAresult.access$000(DVLAresult.java:18)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.sandro.openalprsample.DVLAresult$1.onResponse(DVLAresult.java:44)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.sandro.openalprsample.DVLAresult$1.onResponse(DVLAresult.java:41)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at android.os.Looper.loop(Looper.java:145)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5832)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample D/AndroidRuntime: Shutting down VM
03-26 02:49:43.472 23673-23673/com.sandro.openalprsample E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.sandro.openalprsample, PID: 23673
                                                                           java.lang.NullPointerException: storage == null
                                                                               at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
                                                                               at java.util.Arrays.asList(Arrays.java:155)
                                                                               at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
                                                                               at com.sandro.openalprsample.CustomList.<init>(CustomList.java:21)
                                                                               at com.sandro.openalprsample.DVLAresult.showJSON(DVLAresult.java:61)
                                                                               at com.sandro.openalprsample.DVLAresult.access$000(DVLAresult.java:18)
                                                                               at com.sandro.openalprsample.DVLAresult$1.onResponse(DVLAresult.java:44)
                                                                               at com.sandro.openalprsample.DVLAresult$1.onResponse(DVLAresult.java:41)
                                                                               at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                               at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                               at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

2 个解决方案

#1


1  

Unfortunately I don't follow your code. Base on what you have provide I don't see any JSON Array. As an extension to this response I made few modifications and access the data in the JSON object. Here are the additions.

不幸的是我不遵循你的代码。根据您提供的内容,我没有看到任何JSON数组。作为此响应的扩展,我进行了一些修改并访问JSON对象中的数据。这是增加的内容。

Updates to MainActivity.java from here

从这里更新MainActivity.java

HandleJSON obj = new HandleJSON("");
obj.readAndParseJSON(responseOutput.toString());
output.append(System.getProperty("line.separator") + "\nJSON Object... " + System.getProperty("line.separator") + "Make : " + obj.getMake() + "\nModel : " + obj.getModel());
output.append("\nSix Month Rate  : " + obj.getSixMonthRate() + "\nTwelve Month Rate : " + obj.getTwelveMonthRate() + "\nDate of First Registration : " + obj.getDateofFirstRegistrationegistration());
output.append("\nYear of Manufacture : " + obj.getYearOfManufacture() + "\nCylinder Capacity : " + obj.getCylinderCapacity() + "\nCO2 Emmissions : " + obj.getCo2Emissions());

HandleJSON.java

import org.json.JSONObject;
import android.annotation.SuppressLint;

public class HandleJSON {
    private String make = "make";
    private String model = "model";
    private String sixMonthRate = "sixMonthRate";
    private String twelveMonthRate = "twelveMonthRate";
    private String dateofFirstRegistration = "dateofFirstRegistration";
    private String yearOfManufacture = "yearOfManufacture";
    private String cylinderCapacity = "cylinderCapacity";
    private String co2Emissions= "co2Emissions";

    public HandleJSON(String url) {this.urlString = url;}
    public void setURL(String url){ this.urlString = url;}
    public String getMake() {return make;}
    public String getModel() {return model;}
    public String getSixMonthRate() {return sixMonthRate;}
    public String getTwelveMonthRate() {return twelveMonthRate;}
    public String getDateofFirstRegistrationegistration() {return dateofFirstRegistration;}    
    public String getYearOfManufacture() {return yearOfManufacture;}
    public String getCylinderCapacity() {return cylinderCapacity;}
    public String getCo2Emissions() {return co2Emissions;}

    @SuppressLint("NewApi")
    public void readAndParseJSON(String in) {
        try {
            JSONObject reader = new JSONObject(in);
            make = reader.getString("make");
            model = reader.getString("model");
            sixMonthRate = reader.getString("sixMonthRate");
            twelveMonthRate = reader.getString("twelveMonthRate");
            dateofFirstRegistration= reader.getString("dateOfFirstRegistration");
            yearOfManufacture= reader.getString("yearOfManufacture");
            cylinderCapacity= reader.getString("cylinderCapacity");
            co2Emissions= reader.getString("co2Emissions");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Here is the output

这是输出

ParseJson.java,解析结果如果没有数组名?

References:

#2


0  

Is DVLA JSON DATABASE supposed to be the contents of JSON_ARRAY?

DVLA JSON DATABASE应该是JSON_ARRAY的内容吗?

If so then you should be calling getJsonObject instead of getJsonArray and then iterate through them as such:

如果是这样,那么你应该调用getJsonObject而不是getJsonArray,然后迭代它们:

for(String key : vehicle.keySet() {
    // Do something with the key and object.
    Object obj = vehicle.get(key);
}

If not, I guess I didn't fully understand your question

如果没有,我想我没有完全理解你的问题

Edited

I'm not sure where you get your `json' value but I'm gonna assume it is the contents of DVLA_JSON_DATABASE

我不确定你在哪里得到你的`json'值,但我会假设它是DVLA_JSON_DATABASE的内容

If not, just copy paste the following:

如果没有,只需复制粘贴以下内容:

JSONObject jsonObject = new JSONObject("{\"make\":\"VOLKSWAGEN\",\"model\":\"Tiguan\",\"sixMonthRate\":\"Unknown\",\"twelveMonthRate\":\"Unknown\",\"dateOfFirstRegistration\":\"23 July 2009\",\"yearOfManufacture\":\"2009\",\"cylinderCapacity\":\"1968cc\",\"co2Emissions\":\"167 g/km\",\"fuelType\":\"DIESEL\",\"taxStatus\":\"Taxed and due\",\"colour\":\"SILVER\",\"typeApproval\":\"M1\",\"wheelPlan\":\"2 AXLE RIGID BODY\",\"revenueWeight\":\"Not available\",\"taxDetails\":\"Tax due: 01 April 2016\",\"motDetails\":\"Expires: 21 April 2016\",\"taxed\":true,\"mot\":true}");

in place of json

代替json

Now for some code:

现在为一些代码:

try {
        jsonObject = new JSONObject(json);

        String make = jsonObject.getString("make");
        String model = jsonObject.getString("model");
        String sixMonthRate = jo.getString("sixMonthRate");
        // Do something with these variables

    } catch (JSONException e) {
        e.printStackTrace();
    }

You might've noticed but a JSON consists of a key:value. You simply call getString(key) to get a String value. Similarly you would call 'getInt(key)' to get a Integer value

您可能已经注意到,但JSON包含一个键:值。您只需调用getString(key)来获取String值。类似地,您可以调用'getInt(key)'来获取Integer值

That's all there is to it!

这里的所有都是它的!

#1


1  

Unfortunately I don't follow your code. Base on what you have provide I don't see any JSON Array. As an extension to this response I made few modifications and access the data in the JSON object. Here are the additions.

不幸的是我不遵循你的代码。根据您提供的内容,我没有看到任何JSON数组。作为此响应的扩展,我进行了一些修改并访问JSON对象中的数据。这是增加的内容。

Updates to MainActivity.java from here

从这里更新MainActivity.java

HandleJSON obj = new HandleJSON("");
obj.readAndParseJSON(responseOutput.toString());
output.append(System.getProperty("line.separator") + "\nJSON Object... " + System.getProperty("line.separator") + "Make : " + obj.getMake() + "\nModel : " + obj.getModel());
output.append("\nSix Month Rate  : " + obj.getSixMonthRate() + "\nTwelve Month Rate : " + obj.getTwelveMonthRate() + "\nDate of First Registration : " + obj.getDateofFirstRegistrationegistration());
output.append("\nYear of Manufacture : " + obj.getYearOfManufacture() + "\nCylinder Capacity : " + obj.getCylinderCapacity() + "\nCO2 Emmissions : " + obj.getCo2Emissions());

HandleJSON.java

import org.json.JSONObject;
import android.annotation.SuppressLint;

public class HandleJSON {
    private String make = "make";
    private String model = "model";
    private String sixMonthRate = "sixMonthRate";
    private String twelveMonthRate = "twelveMonthRate";
    private String dateofFirstRegistration = "dateofFirstRegistration";
    private String yearOfManufacture = "yearOfManufacture";
    private String cylinderCapacity = "cylinderCapacity";
    private String co2Emissions= "co2Emissions";

    public HandleJSON(String url) {this.urlString = url;}
    public void setURL(String url){ this.urlString = url;}
    public String getMake() {return make;}
    public String getModel() {return model;}
    public String getSixMonthRate() {return sixMonthRate;}
    public String getTwelveMonthRate() {return twelveMonthRate;}
    public String getDateofFirstRegistrationegistration() {return dateofFirstRegistration;}    
    public String getYearOfManufacture() {return yearOfManufacture;}
    public String getCylinderCapacity() {return cylinderCapacity;}
    public String getCo2Emissions() {return co2Emissions;}

    @SuppressLint("NewApi")
    public void readAndParseJSON(String in) {
        try {
            JSONObject reader = new JSONObject(in);
            make = reader.getString("make");
            model = reader.getString("model");
            sixMonthRate = reader.getString("sixMonthRate");
            twelveMonthRate = reader.getString("twelveMonthRate");
            dateofFirstRegistration= reader.getString("dateOfFirstRegistration");
            yearOfManufacture= reader.getString("yearOfManufacture");
            cylinderCapacity= reader.getString("cylinderCapacity");
            co2Emissions= reader.getString("co2Emissions");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Here is the output

这是输出

ParseJson.java,解析结果如果没有数组名?

References:

#2


0  

Is DVLA JSON DATABASE supposed to be the contents of JSON_ARRAY?

DVLA JSON DATABASE应该是JSON_ARRAY的内容吗?

If so then you should be calling getJsonObject instead of getJsonArray and then iterate through them as such:

如果是这样,那么你应该调用getJsonObject而不是getJsonArray,然后迭代它们:

for(String key : vehicle.keySet() {
    // Do something with the key and object.
    Object obj = vehicle.get(key);
}

If not, I guess I didn't fully understand your question

如果没有,我想我没有完全理解你的问题

Edited

I'm not sure where you get your `json' value but I'm gonna assume it is the contents of DVLA_JSON_DATABASE

我不确定你在哪里得到你的`json'值,但我会假设它是DVLA_JSON_DATABASE的内容

If not, just copy paste the following:

如果没有,只需复制粘贴以下内容:

JSONObject jsonObject = new JSONObject("{\"make\":\"VOLKSWAGEN\",\"model\":\"Tiguan\",\"sixMonthRate\":\"Unknown\",\"twelveMonthRate\":\"Unknown\",\"dateOfFirstRegistration\":\"23 July 2009\",\"yearOfManufacture\":\"2009\",\"cylinderCapacity\":\"1968cc\",\"co2Emissions\":\"167 g/km\",\"fuelType\":\"DIESEL\",\"taxStatus\":\"Taxed and due\",\"colour\":\"SILVER\",\"typeApproval\":\"M1\",\"wheelPlan\":\"2 AXLE RIGID BODY\",\"revenueWeight\":\"Not available\",\"taxDetails\":\"Tax due: 01 April 2016\",\"motDetails\":\"Expires: 21 April 2016\",\"taxed\":true,\"mot\":true}");

in place of json

代替json

Now for some code:

现在为一些代码:

try {
        jsonObject = new JSONObject(json);

        String make = jsonObject.getString("make");
        String model = jsonObject.getString("model");
        String sixMonthRate = jo.getString("sixMonthRate");
        // Do something with these variables

    } catch (JSONException e) {
        e.printStackTrace();
    }

You might've noticed but a JSON consists of a key:value. You simply call getString(key) to get a String value. Similarly you would call 'getInt(key)' to get a Integer value

您可能已经注意到,但JSON包含一个键:值。您只需调用getString(key)来获取String值。类似地,您可以调用'getInt(key)'来获取Integer值

That's all there is to it!

这里的所有都是它的!