Suche…


Syntax

  • Objekt : Ein Objekt ist eine ungeordnete Menge von Name / Wert-Paaren. Ein Objekt beginnt mit {(linke Klammer) und endet mit} (rechte Klammer). Jeder Name wird gefolgt von: (Doppelpunkt) und die Name / Wert-Paare werden durch (Komma) getrennt.

  • Array : Ein Array ist eine geordnete Sammlung von Werten. Ein Array beginnt mit [(linke Klammer) und endet mit] (rechte Klammer). Werte werden durch (Komma) getrennt.

  • Wert : Ein Wert kann eine Zeichenfolge in doppelten Anführungszeichen oder eine Zahl oder wahr oder falsch oder null oder ein Objekt oder ein Array sein. Diese Strukturen können verschachtelt werden.

  • String: Ein String ist eine Folge von null oder mehr Unicode - Zeichen in doppelten Anführungszeichen eingewickelt, mit Backslash entkommt. Ein Zeichen wird als einzelne Zeichenfolge dargestellt. Eine Zeichenfolge ist einer C- oder Java-Zeichenfolge sehr ähnlich.

  • Zahl : Eine Zahl ist einer C- oder Java-Zahl sehr ähnlich, außer dass die Oktal- und Hexadezimalformate nicht verwendet werden.

Bemerkungen

In diesem Thema wird das Paket org.json , das im Android SDK enthalten ist.

Einfaches JSON-Objekt analysieren

Betrachten Sie die folgende JSON-Zeichenfolge:

{
  "title": "test",
  "content": "Hello World!!!",
  "year": 2016,
  "names" : [
        "Hannah",
        "David",
        "Steve"
   ]
} 

Dieses JSON-Objekt kann mit folgendem Code analysiert werden:

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());
}

Hier ist ein weiteres Beispiel mit einem in JSONObject geschachtelten JSONArray:

{
    "books":[
      {
        "title":"Android JSON Parsing",
        "times_sold":186
      }
    ]
}

Dies kann mit dem folgenden Code analysiert werden:

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");

Einfaches JSON-Objekt erstellen

Erstellen Sie das JSONObject mithilfe des leeren Konstruktors und fügen Sie Felder mithilfe der Methode put() , die überladen ist, sodass sie mit verschiedenen Typen verwendet werden kann:

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);
}

Die resultierende JSON Zeichenfolge sieht folgendermaßen aus:

{  
   "name":"test",
   "content":"Hello World!!!1",
   "year":2016,
   "value":3.23,
   "member":true,
   "null_value":null
}

Fügen Sie JSONArray zu JSONObject hinzu

// 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();

Die resultierende JSON-Zeichenfolge sieht folgendermaßen aus:

{  
   "the_array":[  
      "ASDF",
      "QWERTY"
   ]
}

Erstellen Sie einen JSON-String mit Nullwert.

Wenn Sie einen JSON-String mit einem Wert von null wie folgt erstellen müssen:

{  
   "name":null
}

Dann müssen Sie die spezielle Konstante JSONObject.NULL verwenden .

Funktionsbeispiel:

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

Bei der Analyse von Json mit Null-String arbeiten

{
    "some_string": null,
    "ather_string": "something"
}

Wenn wir diesen Weg verwenden werden:

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

Wir werden ausgeben:

someString = "null";

Daher müssen wir diese Problemumgehung bereitstellen:

/**
 * 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);
    }
}

Und dann anrufen:

JSONObject json = new JSONObject(jsonStr);
String someString = optNullableString(json, "some_string");
String someString2 = optNullableString(json, "some_string", "");

Und wir werden Output wie erwartet haben:

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

JsonReader zum Lesen von JSON aus einem Stream verwenden

JsonReader liest einen JSON-codierten Wert als JsonReader .

   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);
   }

Erstellen Sie geschachtelte JSON-Objekte

Um geschachtelte JSON-Objekte zu erstellen, müssen Sie einfach ein JSON-Objekt zu einem anderen hinzufügen:

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";
}

Jetzt enthält mainObject einen Schlüssel namens claim mit dem gesamten requestObject als Wert.

Umgang mit dynamischen Schlüsseln für die JSON-Antwort

Dies ist ein Beispiel für den Umgang mit dynamischen Schlüsseln für die Antwort. Hier sind A und B dynamische Schlüssel, es kann alles sein

Antwort

{
  "response": [
    {
      "A": [
        {
          "name": "Tango"
        },
        {
          "name": "Ping"
        }
      ],
      "B": [
        {
          "name": "Jon"
        },
        {
          "name": "Mark"
        }
      ]
    }
  ]
}

Java-Code

// 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);
    }
}

Prüfen Sie, ob Felder in JSON vorhanden sind

Manchmal ist es nützlich zu prüfen, ob ein Feld in Ihrem JSON vorhanden ist oder nicht, um JSONException in Ihrem Code zu vermeiden.

Um dies zu erreichen, verwenden Sie das JSONObject#has(String) oder die Methode wie im folgenden Beispiel:

Beispiel JSON

{
   "name":"James"
}

Java-Code

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".

Aktualisieren der Elemente in der JSON

Beispiel-Json zum Aktualisieren

 {
 "student":{"name":"Rahul", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }

Um den Elementwert im Json zu aktualisieren, müssen wir den Wert zuweisen und aktualisieren.

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);
}

aktualisierter Wert

 {
 "student":{"name":"Kumar", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }


Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow