【问题标题】:ParseJson.java, Parsing result if NO array name?ParseJson.java,如果没有数组名,解析结果?
【发布时间】:2016-03-26 02:05:03
【问题描述】:

这是我的代码:

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 name ,我应该如何更改代码以使其工作?

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

我正在使用本教程 - 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)

【问题讨论】:

  • 你能发布崩溃的堆栈跟踪吗?
  • 如果你有信息数组,那么你需要一个数组名。你能发布你得到的json结果吗
  • @malac shah 更新

标签: java android arrays json


【解决方案1】:

很遗憾,我没有遵循您的代码。根据您提供的内容,我没有看到任何 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();
        }

    }

}

这是输出

参考资料:

【讨论】:

  • 我能问一下,HandleJSON urlString 应该是什么
  • 类 HandleJSON.java 中的 urlString 突出显示为红色,无法理解错误是什么。
  • @J.FOG,没有错误,只是强调了上面的JSON字符串可以使用HandleJSON模块解析。
  • 错误:(20, 13) 错误: 找不到符号变量 urlString
  • 它也不让我运行这个错误的应用程序((((。
【解决方案2】:

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) 即可获取字符串值。 同样,您会调用 'getInt(key)' 来获取整数值

这就是它的全部内容!

【讨论】:

  • 不,我发布了没有数组名,我不明白如何解析没有数组名的JSON(如何修改它以使其工作)
  • 堆栈跟踪表明您没有 jsonarray,而您没有。 jsonArray 的格式为 'jsonArray':(A,B,C)。注意括号。查看文件,您没有任何括号,实际上只有字符串和布尔值。因此,您希望对每个字段使用 getString() 或 getBoolean()。如果你要学习 Android,学习 JSON 是值得的,因为你会经常使用这些。(json.org)
  • 您知道如何在没有数组名称的情况下使其工作吗?目前改为 JSONArray jsonArray = new JSONArray(json);但仍然没有变化
  • 你知道解决办法吗,因为我在这里不知道多久,急着想办法解决它。(
  • 让本教程 simplifiedcoding.net/… 使用这个 JSON - dvlasearch.appspot.com/…
猜你喜欢
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多