转换的JSONObject到JSONArray [英] Converting JSONObject to JSONArray

查看:256
本文介绍了转换的JSONObject到JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在学习用JAVA某些Android编程。我的老师分享这块code的这将消耗一个API,获得它的JSON文件,并将其转换为一个JSONArray文件。然后,他将通过JSONArray迭代,并把它们放到一个ArrayList显示它们到一个活动之前。

问题是,我正在消耗返回API一个JSONObject文件,而不是,我不知道如何正确地将其转换为JSONArray。

 进口android.util.Log;进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;
进口java.io.BufferedInputStream中;
进口java.io.BufferedReader中;
进口java.io.DataOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口java.net.URLEn codeR;
进口的java.util.HashMap;公共类JSONParser {字符串charset =UTF-8;
HttpURLConnection的康涅狄格州;
DataOutputStream类WR;
StringBuilder的结果;
URL urlObj;
JSONArray jObj = NULL;
StringBuilder的sbParams;
串paramsString;公共JSONArray makeHtt prequest(URL字符串,字符串的方法){    sbParams =新的StringBuilder();   如果(method.equals(GET)){
        //请求方法是GET        如果(sbParams.length()!= 0){
            网址+ =? + sbParams.toString();
        }        尝试{
            urlObj =新的URL(网址);            康恩=(HttpURLConnection类)urlObj.openConnection();            conn.setDoOutput(假);            conn.setRequestMethod(GET);
            conn.setRequestProperty(AccountKey,pVU56 + 0hI26DNLeTzlU / DW ==);
            conn.setRequestProperty(UniqueUserId,33c07f2f-b4c0-4151-acd3-e0829b303d2c);
            conn.setRequestProperty(接受,应用/ JSON);            conn.setConnectTimeout(15000);            conn.connect();        }赶上(IOException异常五){
            e.printStackTrace();
        }    }    尝试{
        //接收来自服务器的响应
        在的InputStream =新的BufferedInputStream(conn.getInputStream());
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(中));
        结果=新的StringBuilder();
        串线;
        而((行= reader.readLine())!= NULL){
            result.append(线);
        }        Log.d(JSON分析器,结果:+ result.toString());    }赶上(IOException异常五){
        // e.printStackTrace();
    }    conn.disconnect();    //尝试分析字符串到一个JSON对象
    尝试{        jObj =新JSONArray(result.toString());
    }赶上(JSONException E){
        Log.e(JSON解析器,错误分析数据+ e.toString());
    }    //返回JSON对象
    返回jObj;
}

}

API URL和自定义页眉:

 网​​址:http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability

标题 -

  AccountKey:pVU56 + 0hI26DNLeTzlU / DW ==
UniqueUserId:33c07f2f-b4c0-4151-acd3-e0829b303d2c
接受:应用/ JSON

EDIT2:我用这个自定义标题,让我的原始数据。
http://requestmaker.com/

编辑:这是我得到的JSON

  {
  odata.metadata:http://datamall2.mytransport.sg/ltaodataservice/$metadata#TaxiAvailability,
  值:
    {
      经度:103.84009,
      纵横:1.35989
    },
    {
      经度:103.84679,
      纵横:1.35544
    },
    {
      经度:103.76928,
      纵横:1.4419
    }
    ....
    ]
    }


解决方案

代替添加此 jObj =新JSONArray(result.toString());

 的JSONObject的obj =新的JSONObject(result.toString());
JSONArray ARR = obj.getJSONArray(值);

现在你可以使用 JSONArray 改编你想要的方式。

I'm currently learning some android programming with JAVA. My teacher shared this piece of code which will consume an API, get its JSON file, and convert it to a JSONArray file. Then he will Iterate through that JSONArray and put them into an ArrayList before displaying them onto an activity.

The problem is that the API that I'm consuming returns a JSONObject file instead, and I do not know how to properly convert this to JSONArray.

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONArray jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONArray makeHttpRequest(String url, String method) {

    sbParams = new StringBuilder();

   if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");


            conn.setRequestProperty("AccountKey", "pVU56+0hI26DNLeTzlU/Dw==");
            conn.setRequestProperty("UniqueUserId", "33c07f2f-b4c0-4151-acd3-e0829b303d2c");
            conn.setRequestProperty("accept", "application/json");

            conn.setConnectTimeout(15000);

            conn.connect();

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

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

    } catch (IOException e) {
        // e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {

        jObj = new JSONArray(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

}

API URL and its custom headers:

URL: http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability

headers-

AccountKey: pVU56+0hI26DNLeTzlU/Dw==
UniqueUserId: 33c07f2f-b4c0-4151-acd3-e0829b303d2c
accept: application/json

EDIT2: I use this to get my raw data with custom headers. http://requestmaker.com/

EDIT: This is the JSON that I get.

{
  "odata.metadata": "http://datamall2.mytransport.sg/ltaodataservice/$metadata#TaxiAvailability",
  "value": [
    {
      "Longitude": 103.84009,
      "Latitude": 1.35989
    },
    {
      "Longitude": 103.84679,
      "Latitude": 1.35544
    },
    {
      "Longitude": 103.76928,
      "Latitude": 1.4419
    }
    ....
    ]
    }

解决方案

Add this in place of jObj = new JSONArray(result.toString());

JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");

Now you can use JSONArray arr the way you want.

这篇关于转换的JSONObject到JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆