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

时间:2016-03-26 02:05:04

标签: java android arrays json

这是我的代码:

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();
        }
    }
}

如果我使用DVLA JSON DATABASE并且没有ARRAY名称,我该如何更改代码才能使其正常工作?

目前,如果我按下按钮获取数据,我会在app关闭时得到结果。

我正在使用本教程 - HERE

错误获取

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 个答案:

答案 0 :(得分:0)

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

如果是这样,那么您应该调用getJsonObject而不是getJsonArray,然后按原样进行迭代:

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

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

<强>被修改

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

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

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}");

取代json

现在有些代码:

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();
    }

您可能已经注意到,但JSON包含key:value。 您只需调用getString(key)即可获得String值。 类似地,您可以调用'getInt(key)'来获取整数值

这就是它的全部!

答案 1 :(得分:0)

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

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();
        }

    }

}

这是输出

enter image description here

<强>参考文献: