«Невозможно получить доступ к org.json.JSONStringer.Scope» в Android Studio 3.2.1 - PullRequest
0 голосов
/ 21 ноября 2018

Извините за этот, вероятно, глупый вопрос, я новичок в Java, Android Studio и всем, что с этим связано.Я пытаюсь реализовать простое приложение прогноза погоды для Android на Android Studio 3.2.1, используя DarkSkyApi .Мне удалось получить данные с сервера DarkSky с помощью HttpsURLConnection, StringBuilder и BufferedReader.Однако, когда я пытаюсь создать новый JSONObject (.toString ()), он просто возвращает ноль.Дальнейшие исследования привели меня к .toString () -> JSONObject.java-> JSONStringer, где Android Studio «Не может получить доступ к org.json.JSONStringer.Scope», что, по-видимому, вызывает сбой .toString ().Я добавил JSON-библиотеку, кроме JSONStringer, все, что связано с JSON, похоже, будет работать.Импорт хорошо выглядит для меня.Это неисправный код:

public class JSONStringer {

/** The output data, containing at most one top-level array or object. */
final StringBuilder out = new StringBuilder();

/**
 * Lexical scoping elements within this stringer, necessary to insert the
 * appropriate separator characters (ie. commas and colons) and to detect
 * nesting errors.
 */ 

enum Scope {

    /**
     * An array with no elements requires no separators or newlines before
     * it is closed.
     */
    EMPTY_ARRAY,

    /**
     * A array with at least one value requires a comma and newline before
     * the next element.
     */
    NONEMPTY_ARRAY,

    /**
     * An object with no keys or values requires no separators or newlines
     * before it is closed.
     */
    EMPTY_OBJECT,

    /**
     * An object whose most recent element is a key. The next element must
     * be a value.
     */
    DANGLING_KEY,

    /**
     * An object with at least one name/value pair requires a comma and
     * newline before the next element.
     */
    NONEMPTY_OBJECT,

    /**
     * A special bracketless array needed by JSONStringer.join() and
     * JSONObject.quote() only. Not used for JSON encoding.
     */
    NULL,
}

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

И вот где я получаю нулевой объект

if (responceCode == HttpURLConnection.HTTP_OK)
        {
            Log.i(TAG, "CONNECTION:::" + connection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            Log.i(TAG, "url:::");
            StringBuilder arg = new StringBuilder(1024);
            String tmp="1";
            while(tmp !=null) {
                tmp = reader.readLine();
                arg.append(tmp).append("\n");
            }
            reader.close();
            Log.i(TAG, "Data: " + arg.toString());


            return new JSONObject(arg.toString());
        }
        else{
            return null;
        }

Log.i (TAG, "Data:" + arg.toString ());работает отлично и записывает строку данных, как и должно.Вам нужно что-то еще, чтобы понять это?Заранее спасибо

1 Ответ

0 голосов
/ 21 ноября 2018

Попробуйте это:

JsonObject output = Json.createObjectBuilder()
     .add("data", arg.toString())
     .build();

return output;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...