Android                
            JSON w Androidzie z org.json
        
        
            
    Szukaj…
Składnia
- Obiekt : Obiekt to nieuporządkowany zestaw par nazwa / wartość. Obiekt zaczyna się od {(lewy nawias klamrowy) i kończy się na} (prawy nawias klamrowy). Po każdej nazwie następuje: (dwukropek), a pary nazwa / wartość są oddzielone, (przecinek). 
- Tablica : Tablica to uporządkowana kolekcja wartości. Tablica zaczyna się od [(lewy nawias) i kończy się na] (prawy nawias). Wartości są oddzielone przez (przecinek). 
- Wartość : wartość może być łańcuchem w podwójnych cudzysłowach lub liczbą, wartością prawda lub fałszem lub wartością zerową, albo obiektem lub tablicą. Struktury te można zagnieżdżać. 
- Łańcuch : Łańcuch jest sekwencją zero lub więcej znaków Unicode, owiniętych podwójnymi cudzysłowami, z użyciem znaków odwrotnego ukośnika. Znak jest reprezentowany jako ciąg jednego znaku. Ciąg jest bardzo podobny do łańcucha C lub Java. 
- Liczba : liczba jest bardzo podobna do liczby C lub Java, z tym wyjątkiem, że nie są używane formaty ósemkowe i szesnastkowe. 
Uwagi
 Ten temat dotyczy korzystania z pakietu org.json zawartego w zestawie Android SDK. 
Analizuj prosty obiekt JSON
Rozważ następujący ciąg JSON:
{
  "title": "test",
  "content": "Hello World!!!",
  "year": 2016,
  "names" : [
        "Hannah",
        "David",
        "Steve"
   ]
} 
Ten obiekt JSON można przeanalizować za pomocą następującego kodu:
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) {
    Log.w(TAG,"Could not parse JSON. Error: " + e.getMessage());
}
Oto kolejny przykład z JSONArray zagnieżdżoną w JSONObject:
{
    "books":[
      {
        "title":"Android JSON Parsing",
        "times_sold":186
      }
    ]
}
Można to przeanalizować za pomocą następującego kodu:
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");
Tworzenie prostego obiektu JSON
 Utwórz JSONObject za pomocą pustego konstruktora i dodaj pola za pomocą metody put() , która jest przeciążona, dzięki czemu można jej używać z różnymi typami: 
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) {
    Log.e(TAG, "Failed to create JSONObject", e);
}
 Wynikowy ciąg JSON wygląda następująco: 
{  
   "name":"test",
   "content":"Hello World!!!1",
   "year":2016,
   "value":3.23,
   "member":true,
   "null_value":null
}
Dodaj JSONArray do 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();
Wynikowy ciąg JSON wygląda następująco:
{  
   "the_array":[  
      "ASDF",
      "QWERTY"
   ]
}
Utwórz ciąg JSON o wartości null.
 Jeśli chcesz utworzyć ciąg JSON o wartości null takiej jak ta: 
{  
   "name":null
}
Następnie musisz użyć specjalnej stałej JSONObject.NULL .
Przykład działania:
jsonObject.put("name", JSONObject.NULL);
Praca z ciągiem zerowym podczas analizowania JSON
{
    "some_string": null,
    "ather_string": "something"
}
Jeśli użyjemy w ten sposób:
JSONObject json = new JSONObject(jsonStr);
String someString = json.optString("some_string");
Będziemy mieli wyjście:
someString = "null";
Musimy więc zastosować to obejście:
/**
 * 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.
 * <strong></strong>
 */
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.
 * <strong></strong>
 */
public static String optNullableString(JSONObject jsonObject, String key, String fallback) {
    if (jsonObject.isNull(key)) {
        return fallback;
    } else {
        return jsonObject.optString(key, fallback);
    }
}
A potem zadzwoń:
JSONObject json = new JSONObject(jsonStr);
String someString = optNullableString(json, "some_string");
String someString2 = optNullableString(json, "some_string", "");
I będziemy mieć Wyjście zgodnie z oczekiwaniami:
someString = null; //not "null"
someString2 = "";
Korzystanie z JsonReader do odczytu JSON ze strumienia
 JsonReader odczytuje wartość zakodowaną w JSON jako strumień tokenów. 
   public List<Message> readJsonStream(InputStream in) throws IOException {
     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
     try {
       return readMessagesArray(reader);
     } finally {
       reader.close();
     }
   }
   public List<Message> readMessagesArray(JsonReader reader) throws IOException {
     List<Message> messages = new ArrayList<Message>();
     reader.beginArray();
     while (reader.hasNext()) {
       messages.add(readMessage(reader));
     }
     reader.endArray();
     return messages;
   }
   public Message readMessage(JsonReader reader) throws IOException {
     long id = -1;
     String text = null;
     User user = null;
     List<Double> geo = null;
     reader.beginObject();
     while (reader.hasNext()) {
       String name = reader.nextName();
       if (name.equals("id")) {
         id = reader.nextLong();
       } 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<Double> readDoublesArray(JsonReader reader) throws IOException {
     List<Double> doubles = new ArrayList<Double>();
     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);
   }
Utwórz zagnieżdżony obiekt JSON
Aby utworzyć zagnieżdżony obiekt JSON, wystarczy po prostu dodać jeden obiekt JSON do drugiego:
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) {
    return "JSON Error";
}
 Teraz mainObject zawiera klucz o nazwie claim z całym requestObject jako wartością. 
Obsługa klucza dynamicznego dla odpowiedzi JSON
 To jest przykład obsługi dynamicznego klucza odpowiedzi. Tutaj A i B to klucze dynamiczne, może to być wszystko 
Odpowiedź
{
  "response": [
    {
      "A": [
        {
          "name": "Tango"
        },
        {
          "name": "Ping"
        }
      ],
      "B": [
        {
          "name": "Jon"
        },
        {
          "name": "Mark"
        }
      ]
    }
  ]
}
Kod Java
// 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<ArrayList<String>> declared globally
    nodes = new ArrayList<ArrayList<String>>();
    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 ArrayList<String> declared globally
                nameList = new ArrayList<String>();
               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);
    }
}
Sprawdź istnienie pól w JSON
 Czasami warto sprawdzić, czy pole JSON jest obecne lub nieobecne, aby uniknąć JSONException w kodzie. 
 Aby to osiągnąć, użyj JSONObject#has(String) lub metody, jak w poniższym przykładzie: 
Próbka JSON
{
   "name":"James"
}
Kod Java
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".
Aktualizacja elementów w JSON
przykładowy Json do aktualizacji
 {
 "student":{"name":"Rahul", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }
Aby zaktualizować wartość elementów w Jsonie, musimy przypisać wartość i zaktualizować.
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) {
    Log.e(TAG, "Failed to create JSONObject", e);
}
zaktualizowana wartość
 {
 "student":{"name":"Kumar", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }