Java JSONObject.getJSONArray всегда возвращает ноль - PullRequest
0 голосов
/ 06 января 2020

Я хочу использовать Google Distance Matrix API, чтобы получить продолжительность, необходимую для перемещения между двумя точками. Но когда я пытаюсь получить длительность из возвращенных данных (JSON в кодировке), метод getJSONArray всегда возвращает ноль.

Вот данные, отправленные Google:

{
   "destination_addresses" : [ "Rome, Metropolitan City of Rome, Italy" ],
   "origin_addresses" : [ "Berlin, Germany" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,501 km",
                  "value" : 1501458
               },
               "duration" : {
                  "text" : "15 hours 5 mins",
                  "value" : 54291
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

И здесь это метод для получения продолжительности:

public static int getDurationFromJSON(String json){
    try {
        JSONObject jsonObj = new JSONObject(json)
                .getJSONArray("rows")
                .getJSONObject(0)
                .getJSONArray ("elements")
                .getJSONObject(0)
                .getJSONObject("duration");

        return (int)(jsonObj.getInt("value") / 60.0f + 0.5f);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return -1;
}

getJSONArray ("lines") возвращает ноль.

Ответы [ 2 ]

0 голосов
/ 06 января 2020

Хорошо, вот решение. Не доверяйте орг. json. * Используйте Gson:

Json -Данные:

{
   "destination_addresses" : [ "Rome, Metropolitan City of Rome, Italy" ],
   "origin_addresses" : [ "Berlin, Germany" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,501 km",
                  "value" : 1501458
               },
               "duration" : {
                  "text" : "15 hours 5 mins",
                  "value" : 54291
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Создать объект для результата:

public class DirectionMatrixResult {
    private String[] destination_addresses;
    private String[] origin_addresses;

    private DirectionMatrixResultRow[] rows;

    public DirectionMatrixResultRow[] getRows() {
        return rows;
    }

    public String[] getDestination_addresses() {
        return destination_addresses;
    }

    public String[] getOrigin_addresses() {
        return origin_addresses;
    }

    public void setDestination_addresses(String[] destination_addresses) {
        this.destination_addresses = destination_addresses;
    }

    public void setOrigin_addresses(String[] origin_addresses) {
        this.origin_addresses = origin_addresses;
    }

    public void setRows(DirectionMatrixResultRow[] rows) {
        this.rows = rows;
    }
}

public class DirectionMatrixResultRow {
    private DirectionMatrixResultElement[] elements;

    public DirectionMatrixResultElement[] getElements() {
        return elements;
    }

    public void setElements(DirectionMatrixResultElement[] elements) {
        this.elements = elements;
    }
}

public class DirectionMatrixResultElement {
    private DirectionMatrixResultElementValue distance;
    private DirectionMatrixResultElementValue duration;
    private String status;

    public DirectionMatrixResultElementValue getDistance() {
        return distance;
    }

    public DirectionMatrixResultElementValue getDuration() {
        return duration;
    }

    public String getStatus() {
        return status;
    }

    public void setDistance(DirectionMatrixResultElementValue distance) {
        this.distance = distance;
    }

    public void setDuration(DirectionMatrixResultElementValue duration) {
        this.duration = duration;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

public class DirectionMatrixResultElementValue {
    private String text;
    private long value;

    public long getValue() {
        return value;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setValue(long value) {
        this.value = value;
    }
}

Тогда Звоните:

public static int getDurationFromJSON(String json){
    try {
        Gson gson = new Gson();
        DirectionMatrixResult result = gson.fromJson(json, DirectionMatrixResult.class);
        return (int)(result.getRows()[0].getElements()[0].getDuration().getValue() / 60.0f + 0.0f);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return -1;
}
0 голосов
/ 06 января 2020

Я не уверен, почему вы получаете нулевое значение, но эта строка кажется чрезмерной:

(int)(Integer.parseInt(String.valueOf(jsonObj.getInt("value"))) / 60.0f + 0.5f);

JsonObj.getInt ("Value) собирается вернуть int, почему вы превращаете это в строка, только чтобы затем проанализировать его обратно в Int и затем снова привести его обратно к INT?

Это можно упростить до простого вида

 return(int)((jsonObj.getInt("value")/60.0f) +0.5f)

Что касается нуля, я использовал бы отладчик и проверил бы передаваемый JSON и убедился бы, что это именно то, что вы думаете.

Также, как и другие предлагали, использовать что-то вроде restTemplate для автоматического разбора json на нативный сопоставленные объекты сделают вашу жизнь проще.

...