我应该如何从json url或json创建JSONObject和JSONArray

时间:2017-01-05 09:52:47

标签: android json parsing

我的JSON:

{
    "response_code": 200,
    "error": false,
    "train_name": "KCG YPR EXP",
    "train_num": "17603",
    "pnr": "1234567890",
    "failure_rate": 19.346153846153847,
    "doj": "20-8-2015",
    "chart_prepared": "Y",
    "class": "SL",
    "total_passengers": 2,
    "train_start_date": {
        "month": 8,
        "year": 2015,
        "day": 20
    },
    "from_station": {
        "code": "KCG",
        "name": "KACHEGUDA"
    },
    "boarding_point": {
        "code": "KCG",
        "name": "KACHEGUDA"
    },
    "to_station": {
        "code": "YPR",
        "name": "YESVANTPUR JN"
    },
    "reservation_upto": {
        "code": "YPR",
        "name": "YESVANTPUR JN"
    },
    "passengers": [
        {
            "no": 1,
            "booking_status": "S7,58,GN",
            "current_status": "S7,58",
            "coach_position": 9
        },
        {
            "no": 2,
            "booking_status": "S7,59,GN",
            "current_status": "S7,59",
            "coach_position": 9
        }
    ]
}

到目前为止我做了什么:

if(jsonStr!=null)
        {
            try
            {
                JSONObject object=new JSONObject(jsonStr);
                JSONArray jsonArray=object.getJSONArray("passengers");
                for (int i=0;i<=jsonArray.length();i++)
                {
                    JSONObject o=jsonArray.getJSONObject(i);
                    int no= Integer.parseInt(o.optString("no").toString());
                    String booking_status=o.getString("Booking Status");
                    String current_status=o.getString("Current Status");
                    String coach_position=o.getString("Coach Position");

                    JSONObject data=o.getJSONObject("details");
                    String train_name = data.getString("Train Name");
                    int  train_num = Integer.parseInt(data.optString("train number").toString());
                    int pnr = Integer.parseInt(data.optString("pnr").toString());
                    String chart_prepared = data.getString("Chart Prepared");
                    int total_passengers=Integer.parseInt(data.optString("total passengers").toString());

                    JSONObject date=data.getJSONObject("tarin_start_date");
                    int month=Integer.parseInt(data.optString("month").toString());
                    int year=Integer.parseInt(data.optString("year").toString());
                    int day=Integer.parseInt(data.optString("day").toString());


                    JSONObject co=date.getJSONObject("from_station");
                    String code=co.getString("code");
                    String name=co.getString("name");

                    JSONObject co1=co.getJSONObject("boarding_point");
                    String code1=co1.getString("code");
                    String name1=co1.getString("name");

                    JSONObject co2=co1.getJSONObject("to_station");
                    String code2=co2.getString("code");
                    String name2=co2.getString("name");

                    JSONObject co3=co2.getJSONObject("from_station");
                    String code3=co3.getString("code");
                    String name3=co3.getString("name");

                    HashMap<String,String> dtail=new HashMap<>();
                    dtail.put("no", String.valueOf(no));
                    dtail.put("Booking Staus",booking_status);
                    dtail.put("Current Staus",current_status);
                    dtail.put("Coach Positon",coach_position);
                    dtail.put("Train Name",train_name);
                    dtail.put("Train Number", String.valueOf(train_num));
                    dtail.put("pnr", String.valueOf(pnr));
                    dtail.put("chart prepared",chart_prepared);
                    dtail.put("total passengers", String.valueOf(total_passengers));
                    dtail.put("month", String.valueOf(month));
                    dtail.put("year", String.valueOf(year));
                    dtail.put("day", String.valueOf(day));
                    dtail.put("code",code);
                    dtail.put("name",name);
                    dtail.put("code",code1);
                    dtail.put("name",name1);
                    dtail.put("code",code2);
                    dtail.put("name",name2);
                    dtail.put("code",code3);
                    dtail.put("name",name3);

                    dataList.add(dtail);


                }
            }
            catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });

            }

        }
        else
        {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG).show();
                }
            });
        }
return null;
        }

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助: -

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dummy);
 String str = "{\n" +
                "    \"response_code\": 200,\n" +
                "    \"error\": false,\n" +
                "    \"train_name\": \"KCG YPR EXP\",\n" +
                "    \"train_num\": \"17603\",\n" +
                "    \"pnr\": \"1234567890\",\n" +
                "    \"failure_rate\": 19.346153846153847,\n" +
                "    \"doj\": \"20-8-2015\",\n" +
                "    \"chart_prepared\": \"Y\",\n" +
                "    \"class\": \"SL\",\n" +
                "    \"total_passengers\": 2,\n" +
                "    \"train_start_date\": {\n" +
                "        \"month\": 8,\n" +
                "        \"year\": 2015,\n" +
                "        \"day\": 20\n" +
                "    },\n" +
                "    \"from_station\": {\n" +
                "        \"code\": \"KCG\",\n" +
                "        \"name\": \"KACHEGUDA\"\n" +
                "    },\n" +
                "    \"boarding_point\": {\n" +
                "        \"code\": \"KCG\",\n" +
                "        \"name\": \"KACHEGUDA\"\n" +
                "    },\n" +
                "    \"to_station\": {\n" +
                "        \"code\": \"YPR\",\n" +
                "        \"name\": \"YESVANTPUR JN\"\n" +
                "    },\n" +
                "    \"reservation_upto\": {\n" +
                "        \"code\": \"YPR\",\n" +
                "        \"name\": \"YESVANTPUR JN\"\n" +
                "    },\n" +
                "    \"passengers\": [\n" +
                "        {\n" +
                "            \"no\": 1,\n" +
                "            \"booking_status\": \"S7,58,GN\",\n" +
                "            \"current_status\": \"S7,58\",\n" +
                "            \"coach_position\": 9\n" +
                "        },\n" +
                "        {\n" +
                "            \"no\": 2,\n" +
                "            \"booking_status\": \"S7,59,GN\",\n" +
                "            \"current_status\": \"S7,59\",\n" +
                "            \"coach_position\": 9\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        parseJson(str);
}


   private void parseJson(String jsonStr) {
    HashMap<String, String> dtail = new HashMap<>();
    if (jsonStr != null) {
        try {
            JSONObject object = new JSONObject(jsonStr);
            int responseCode = object.getInt("response_code");
            boolean error = object.getBoolean("error");
            String train_name = object.getString("train_name");
            int train_num = object.getInt("train_num");
            int pnr = object.getInt("pnr");
            double failurerate = object.getDouble("failure_rate");
            String dateofJoin = object.getString("doj");
            String chart = object.getString("chart_prepared");
            String Class = object.getString("class");
            int total_passengers = object.getInt("total_passengers");
            JSONObject date = object.getJSONObject("train_start_date");
            int month = date.getInt("month");
            int year = date.getInt("year");
            int day = date.getInt("day");

            JSONObject co = object.getJSONObject("from_station");
            String code = co.getString("code");
            String name = co.getString("name");

            JSONObject co1 = object.getJSONObject("boarding_point");
            String code1 = co1.getString("code");
            String name1 = co1.getString("name");

            JSONObject co2 = object.getJSONObject("to_station");
            String code2 = co2.getString("code");
            String name2 = co2.getString("name");

            JSONObject co3 = object.getJSONObject("from_station");
            String code3 = co3.getString("code");
            String name3 = co3.getString("name");

            JSONArray jsonArray = object.getJSONArray("passengers");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int no = jsonObject.getInt("no");
                String booking_status = jsonObject.getString("booking_status");
                String current_status = jsonObject.getString("current_status");
                int coach_position = jsonObject.getInt("coach_position");
                dtail.put("no", String.valueOf(no));
                dtail.put("booking_status", booking_status);
                dtail.put("current_status", current_status);
                dtail.put("coach_position", String.valueOf(coach_position));
            }
            dtail.put("responseCode", String.valueOf(responseCode));
            dtail.put("error", "" + error);
            dtail.put("Train Name", train_name);
            dtail.put("dateofJoin", dateofJoin);
            dtail.put("chart", chart);
            dtail.put("Class", Class);
            dtail.put("Train Number", String.valueOf(train_num));
            dtail.put("pnr", String.valueOf(pnr));
            dtail.put("FAILURE_RATE", String.valueOf(failurerate));
            dtail.put("total passengers", String.valueOf(total_passengers));
            dtail.put("month", String.valueOf(month));
            dtail.put("year", String.valueOf(year));
            dtail.put("day", String.valueOf(day));
            dtail.put("code", code);
            dtail.put("name", name);
            dtail.put("code", code1);
            dtail.put("name", name1);
            dtail.put("code", code2);
            dtail.put("name", name2);
            dtail.put("code", code3);
            dtail.put("name", name3);

            Log.e("Result------", "" + dtail);

        } catch (final JSONException e) {
            Log.e("tag", "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
            });

        }

    }

}

答案 1 :(得分:0)

这是您的解决方案。

希望这会对你有所帮助。每当您使用JSON时,请检查所有密钥名称。它应始终与响应键名称

相同
<form  name="form" id="form" novalidate>
  <div class="row">

<div ng-repeat="ao in counter"
     ng-class="{ 'has-errors-left' : form.cb_{{ao.id}}.$invalid && {{isRequired}} == true && $first, 
                 'has-errors-right' : form.cb_{{ao.id}}.$invalid && {{isRequired}} == true && $last,
                 'no-errors-left' : form.cb_{{ao.id}}.$valid && {{isRequired}} == true && $first,
                 'no-errors-right' : form.cb_{{ao.id}}.$valid && {{isRequired}} == true && $last }"
     id="border"                                       
     class="col col-33 item item-divider removeDividerColor parentDiv">
         <a class="button button-icon icon answerOption_{{ao.id}} answerOptionCB childDiv"
            ng-class="{ 'ion-ios-checkmark-outline': checkStatus === false, 'ion-ios-checkmark': checkStatus === true }"
            id="cb_{{ao.id}}"
            name="cb_{{ao.id}}" on-tap="checkStatus = !checkStatus"
            ng-required="!getRequired(isRequired, ao.id)"
            ng-init="checkStatus = false"
            ng-model="checkStatus">{{ao.Text}}
        </a>             
     </div>
  </div>
</form>