从JSONArray的一个元素创建Java Array

时间:2019-02-19 19:46:27

标签: java arrays json url

我在此URL处有一个JSON数组:     https://gcc.azure-api.net/traffic/v1/movement/now

它采用以下形式:

[
    {
        "type": "irrelevant",
        "lastUpdate": "irrelevant",
        "batchIdentifier": "irrelevant",
        "site": "Irrelevant",
        "timestamp": "irrelevant",
        "flow": 18,
        "concentration": "irrelevant",
        "id": "irrelevant",
        "_id": "irrelevant"
    },
    {
        "type": "irrelevant",
        "lastUpdate": "irrelevant",
        "batchIdentifier": "irrelevant",
        "site": "Irrelevant"
        "timestamp": "irrelevant",
        "flow": 26,
        "concentration": "irrelevant",
        "id": "irrelevant",
        "_id": "irrelevant"
    }
]

我需要能够为该数组的每个元素获取变量“ flow”的这些值,并将其放入整数的Java数组中。我需要它来不断下载JSON以使其实时工作,因此必须从URL进行解析,但是我确实在寻找任何可行的方法来做到这一点而又不使我的应用程序崩溃。

以下是我抛出的一种方法,它只是行不通,它只是现在对我有用的各种解决方案的组合,谢谢您的解释。

public static void main() {

    float[] flowArray = null;

    try {
        JSONArray json = new JSONArray(getText("https://gcc.azure-api.net / traffic / v1 / movement / now"));
        int len = json.length();

        //iterate loop
        for (int i = 0; i < len; i++) {
            JSONObject jsonObject = json.getJSONObject(i);
            String flow = jsonObject.getString("flow");

            float flowNum = Float.parseFloat(flow);
            flowArray[i] = flowNum;
        }

    } catch (Exception Ex) {
        Log.e(TAG, "unexpected exception");
    }
}

public String getText(String url) throws Exception {
    URL website = new URL("https://gcc.azure-api.net/traffic/v1/movement/now");
    URLConnection connection = website.openConnection();
    BufferedReader in = new BufferedReader(new
            InputStreamReader(connection.getInputStream(), "UTF8"));

    StringBuilder response = new StringBuilder();
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        response.append(inputLine);

    in.close();

    return response.toString();
}

3 个答案:

答案 0 :(得分:0)

请参见下面的工作示例。一些评论:

  1. JSON中flow的值不在括号中。 →它不是字符串而是数字。使用.getInt(...)代替.getString(...)
  2. 初始化数组而不是null:float[] flowArray = null;int[] flowArray = new int[len];
  3. 如果将方法main(...)用作应用程序的入口点,则该方法应为静态。
    public static String getText(String url) throws Exception {
        URL website = new URL(url);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader( new 
                InputStreamReader(connection.getInputStream(),"UTF8"));
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            response.append(inputLine);
        in.close();
        return response.toString();
    }

    public static void main(String[] args) {
        try {
            JSONArray json = new JSONArray(getText(
                    "https://gcc.azure-api.net/traffic/v1/movement/now"));
            int len = json.length();
            int[] flowArray = new int[len];
            //iterate loop
            for (int i = 0; i < len; i++) {
                JSONObject jsonObject = json.getJSONObject(i);
                flowArray[i] = jsonObject.getInt("flow"); 
            }
        } catch (Exception Ex) {
            Ex.printStackTrace();
        }
    }

答案 1 :(得分:0)

我一开始就不会使用原始数组。使用更高级别的Collection<T>实现,例如List<T>

final JSONArray jsonArray = new JSONArray(getText("..."));
final List<String> flows = new ArrayList(jsonArray.length());

for (int i = 0; i < jsonArray.length(); i++) {
   final JSONObject jsonObject = jsonArray.getJSONObject(i);
   final int flow = jsonObject.getInt("flow");
   flows.add(flow);
}

return flows;

答案 2 :(得分:0)

如果可以使用JsonPath库。用法示例:

import com.jayway.jsonpath.JsonPath;

import java.net.URL;
import java.util.List;

public class JsonPathApp {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://gcc.azure-api.net/traffic/v1/movement/now");

        List<Integer> flows = JsonPath.parse(url).read("$[*].flow");
        System.out.println(flows);
    }
}

上面的代码显示:

[13,35,0,18,4,9,11,0,18,18,0,0,0,13,14,0,5,4,4,9,22,18,22,4,0,22,0,45,13,9,31,28,4,2,9,0,0,0,9,9,13,10,14,9,0,13,18,31,33,0]

但是,如果您确实需要使用JSONArray,可以按照以下步骤操作:

List<Integer> flows = new ArrayList<>();
JSONArray objects = JSONArray.fromObject(json);
objects.iterator().forEachRemaining(o -> flows.add(((JSONObject) o).getInt("flow")));
System.out.println(flows)

其中json参数为StringJSON*类来自net.sf.json.*包。