Java org json android

Android
JSON в Android с org.json

Этот org.json посвящен использованию пакета org.json , который включен в Android SDK.

Разбирайте простой объект JSON

Рассмотрим следующую строку JSON:

Этот объект JSON может быть проанализирован с использованием следующего кода:

try < // create a new instance from a string JSONObject jsonObject = new JSONObject(jsonAsString); String title = jsonObject.getString("title"); String content = jsonObject.getString("content"); int year = jsonObject.getInt("year"); JSONArray names = jsonObject.getJSONArray("names"); //for an array of String objects >catch (JSONException e)

Вот еще один пример: JSONArray, вложенный внутри JSONObject:

Это может быть проанализировано следующим кодом:

JSONObject root = new JSONObject(booksJson); JSONArray booksArray = root.getJSONArray("books"); JSONObject firstBook = booksArray.getJSONObject(0); String title = firstBook.getString("title"); int timesSold = firstBook.getInt("times_sold"); 

Создание простого объекта JSON

Создайте JSONObject с помощью пустого конструктора и добавьте поля, используя метод put() , который перегружен, чтобы он мог использоваться с различными типами:

try < // Create a new instance of a JSONObject final JSONObject object = new JSONObject(); // With put you can add a name/value pair to the JSONObject object.put("name", "test"); object.put("content", "Hello World. 1"); object.put("year", 2016); object.put("value", 3.23); object.put("member", true); object.put("null_value", JSONObject.NULL); // Calling toString() on the JSONObject returns the JSON in string format. final String json = object.toString(); >catch (JSONException e)

Полученная строка JSON выглядит так:

Добавить JSONArray в JSONObject

// Create a new instance of a JSONArray JSONArray array = new JSONArray(); // With put() you can add a value to the array. array.put("ASDF"); array.put("QWERTY"); // Create a new instance of a JSONObject JSONObject obj = new JSONObject(); try < // Add the JSONArray to the JSONObject obj.put("the_array", array); >catch (JSONException e) < e.printStackTrace(); >String json = obj.toString(); 

Полученная строка JSON выглядит так:

Создайте строку JSON с нулевым значением.

Если вам нужно создать строку JSON со значением null например:

Затем вам нужно использовать специальную константу JSONObject.NULL .

Пример функционирования:

jsonObject.put("name", JSONObject.NULL); 

Работа с нулевой строкой при разборе json

Если мы будем использовать этот способ:

JSONObject json = new JSONObject(jsonStr); String someString = json.optString("some_string"); 

Поэтому мы должны обеспечить это обходное решение:

/** * According to http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null * we need to provide a workaround to opt string from json that can be null. * */ public static String optNullableString(JSONObject jsonObject, String key) < return optNullableString(jsonObject, key, ""); >/** * According to http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null * we need to provide a workaround to opt string from json that can be null. * */ public static String optNullableString(JSONObject jsonObject, String key, String fallback) < if (jsonObject.isNull(key)) < return fallback; >else < return jsonObject.optString(key, fallback); >> 
JSONObject json = new JSONObject(jsonStr); String someString = optNullableString(json, "some_string"); String someString2 = optNullableString(json, "some_string", ""); 

И мы будем иметь Output, как мы и ожидали:

someString = null; //not "null" someString2 = ""; 

Использование JsonReader для чтения JSON из потока

JsonReader считывает кодированное значение JSON как поток токенов.

 public List readJsonStream(InputStream in) throws IOException < JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try < return readMessagesArray(reader); >finally < reader.close(); >> public List readMessagesArray(JsonReader reader) throws IOException < Listmessages = new ArrayList(); reader.beginArray(); while (reader.hasNext()) < messages.add(readMessage(reader)); >reader.endArray(); return messages; > public Message readMessage(JsonReader reader) throws IOException < long String text = null; User user = null; Listgeo = null; reader.beginObject(); while (reader.hasNext()) < String name = reader.nextName(); if (name.equals("id")) < >else if (name.equals("text")) < text = reader.nextString(); >else if (name.equals("geo") && reader.peek() != JsonToken.NULL) < geo = readDoublesArray(reader); >else if (name.equals("user")) < user = readUser(reader); >else < reader.skipValue(); >> reader.endObject(); return new Message(id, text, user, geo); > public List readDoublesArray(JsonReader reader) throws IOException < Listdoubles = new ArrayList(); reader.beginArray(); while (reader.hasNext()) < doubles.add(reader.nextDouble()); >reader.endArray(); return doubles; > public User readUser(JsonReader reader) throws IOException < String username = null; int followersCount = -1; reader.beginObject(); while (reader.hasNext()) < String name = reader.nextName(); if (name.equals("name")) < username = reader.nextString(); >else if (name.equals("followers_count")) < followersCount = reader.nextInt(); >else < reader.skipValue(); >> reader.endObject(); return new User(username, followersCount); > 

Создание вложенного объекта JSON

Чтобы создать вложенный объект JSON, вам нужно просто добавить один объект JSON к другому:

JSONObject mainObject = new JSONObject(); // Host object JSONObject requestObject = new JSONObject(); // Included object try < requestObject.put("lastname", lastname); requestObject.put("phone", phone); requestObject.put("latitude", lat); requestObject.put("longitude", lon); requestObject.put("theme", theme); requestObject.put("text", message); mainObject.put("claim", requestObject); >catch (JSONException e)

Теперь mainObject содержит ключ, называемый claim с целым requestObject в качестве значения.

Читайте также:  All shopping html category

Обработка динамического ключа для ответа JSON

Это пример того, как обрабатывать динамический ключ для ответа. Здесь A и B являются динамическими ключами, это может быть что угодно

// ResponseData is raw string of response JSONObject responseDataObj = new JSONObject(responseData); JSONArray responseArray = responseDataObj.getJSONArray("response"); for (int i = 0; i < responseArray.length(); i++) < // Nodes ArrayList> declared globally nodes = new ArrayList>(); JSONObject obj = responseArray.getJSONObject(i); Iterator keys = obj.keys(); while(keys.hasNext()) < // Loop to get the dynamic key String currentDynamicKey = (String)keys.next(); // Get the value of the dynamic key JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey); int jsonArraySize = currentDynamicValue.length(); if(jsonArraySize >0) < for (int ii = 0; ii < jsonArraySize; ii++) < // NameList ArrayListdeclared globally nameList = new ArrayList(); if(ii == 0) < JSONObject nameObj = currentDynamicValue.getJSONObject(ii); String name = nameObj.getString("name"); System.out.print("Name = " + name); // Store name in an array list nameList.add(name); >> > nodes.add(nameList); > > 

Проверьте наличие полей на JSON

Иногда бывает полезно проверить наличие или отсутствие поля на вашем JSON, чтобы избежать исключения JSONException в вашем коде.

Для этого используйте JSONObject#has(String) или метод, например, в следующем примере:

Образец JSON

String jsonStr = " < \"name\":\"James\" >"; JSONObject json = new JSONObject(jsonStr); // Check if the field "name" is present String name, surname; // This will be true, since the field "name" is present on our JSON. if (json.has("name")) < name = json.getString("name"); >else < name = "John"; >// This will be false, since our JSON doesn't have the field "surname". if (json.has("surname")) < surname = json.getString("surname"); >else < surname = "Doe"; >// Here name == "James" and surname == "Doe". 

Обновление элементов в JSON

образец json для обновления

Чтобы обновить значение элементов в json, нам нужно назначить значение и обновление.

try < // Create a new instance of a JSONObject final JSONObject object = new JSONObject(jsonString); JSONObject studentJSON = object.getJSONObject("student"); studentJSON.put("name","Kumar"); object.remove("student"); object.put("student",studentJSON); // Calling toString() on the JSONObject returns the JSON in string format. final String json = object.toString(); >catch (JSONException e)

Источник

Читайте также:  Javascript to python translator

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JSON Java for Android developers

Clone this wiki locally

History of JSON-Java and Android

The JSON Specification was originally made in 2001 on the http://json.org/ website and was subsequently codified in RFC 4627 (later updated in RFC 7159) and the source code for this project was maintained on the http://json.org/ website until December 2010 when Douglas Crockford uploaded it to this repository.

In March 2010, Android implemented a «cleanroom» implementation of this project’s API. This means that as of March 2010, this project and Android had the same classes and the same public method definitions. However, this GitHub project does not necessarily match the original implementation as done by the Android team ( JSONTokener.end() is an example of an API method in this repository that is not in Android).

Since March 2010, Android has kept nearly the same API, only adding the JSONObject.wrap method. However, the API for this project has been extended to include many new features including support for BigDecimal, BigInteger, Enums, etc.

As both APIs use the org.json namespace, these API differences sometimes make it hard to reuse code between the two projects and today there are known incompatibilities between them.

At the present time, JSON-Java maintains a level of Java JDK compatibility that allows it to be used by Android developers. This is not a project commitment, but it will be maintained for as long as possible.

Читайте также:  Kotlin flow collect all

Classes that can NOT be used with Android

  • JSONString: Android does not have support for this interface. If your classes implement this interface and are used on Android, the JSONObject and JSONArray classes will not output your implementation of toJSONString()

Naming conflict with JSON-Java:

Android has the following classes defined:

  • JSON.java: unique to Android no conflict
  • JSONArray.java: conflict
  • JSONException.java: conflict
  • JSONObject.java: conflict
  • JSONStringer.java: conflict
  • JSONTokener.java: conflict

The Android SDK already includes a subset of JSON-Java functionality. The Android package name is org.json, which conflicts with this project. Even if Android works with us to fix this problem, there is still the problem of this code being included in existing Android releases. So, here are some workarounds:

  • If all you want is basic, no-frills functionality, with no recent bug fixes, then just use the built in Android package.
  • If you want to include the JSON-Java lib for functionality only found in JSON-Java. For example, XML-JSON transformations provided by XML.java and other classes, then this may result in run time errors due to the conflict between the built-in org.json package and the JSON-Java org.json package. In this case, you may wish to refactor the JSON-Java source and build/import a local version of JSON-Java with a different package name.
  • For the XML problem, you may wish to try the workaround found here, where the problem is solved using a recursive copy: https://github.com/AppWerft/Ti.XML2Json/blob/master/android/src/de/appwerft/remotexml/JSON.java
  • PR #350 modifies the library to better support the API as ported to Android. To use the code in the PR you would need to NOT use this library’s classes that are provided by Android (JSONArray, JSONException, JSONObject, JSONStringer, JSONTokener). By excluding these classes, your code and the remaining classes in this library would use the classes provided by Android. One known incompatibility still remaining in the PR is that the Android JSONException class only provides a single constructor JSONException(String) and does not provide the options to pass exception causes. If your code never hits an exception, then this should not be an issue, but if it does, some places in the code may instead try to call JSONException(String, Throwable) or JSONException(Throwable) which are not available. This will cause a java.lang.NoSuchMethodError exception to be thrown instead.

Источник

Оцените статью