Comment analyser un tableau JSON (pas un objet Json) dans Android


J'ai du mal à trouver un moyen d'analyser JSONArray. Cela ressemble à ceci:

[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

Je sais comment l'analyser si le JSON a été écrit différemment (en d'autres termes, si j'avais renvoyé un objet json au lieu d'un tableau d'objets). Mais c'est tout ce que j'ai et je dois aller avec.

*EDIT: C'est un json valide. J'ai créé une application iPhone en utilisant ce json, maintenant je dois le faire pour Android et je ne peux pas le comprendre. Il y a beaucoup d'exemples là-bas, mais ils sont tous liés à JSONObject. Je besoin de quelque chose pour JSONArray.

Quelqu'un peut-il me donner un indice, un tutoriel ou un exemple?

Très apprécié !

Author: SteBra, 2013-09-24

10 answers

Utilisez l'extrait de code suivant pour analyser le JsonArray.

JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String name = jsonobject.getString("name");
    String url = jsonobject.getString("url");
}

J'espère que ça aide.

 106
Author: Spring Breaker, 2016-03-23 11:54:48

Je vais juste donner un peu de Jackson exemple:

Créez d'abord un support de données qui a les champs de la chaîne JSON

// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
    @JsonProperty("name")
    public String mName;

    @JsonProperty("url")
    public String mUrl;
}

Et analyser la liste des détenteurs de noms de domaine

String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString, 
    new TypeReference<ArrayList<MyDataHolder>>() {});

Utilisation des éléments de la liste

String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
 22
Author: vilpe89, 2013-09-24 10:07:37
public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Sortie:

name1
url1
name2
url2
 18
Author: Maxim Shoustin, 2013-09-24 09:12:07

Créer une classe pour contenir les objets.

public class Person{
   private String name;
   private String url;
   //Get & Set methods for each field
}

, Puis désérialiser comme suit:

Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String

Article de Référence: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

 9
Author: Kevin Bowersox, 2013-09-24 09:08:01

Dans cet exemple, il y a plusieurs objets dans un tableau json. C'est-à-dire

C'est le tableau json: [{"name":"nom1","url":"url1"},{"name":"nom2","url":"url2"},...]

C'est un objet: {"nom":"nom1","url":"url1"}

En supposant que vous avez obtenu le résultat d'une variable de chaîne appelée jSonResultString:

JSONArray arr = new JSONArray(jSonResultString);

  //loop through each object
  for (int i=0; i<arr.length(); i++){

  JSONObject jsonProductObject = arr.getJSONObject(i);
  String name = jsonProductObject.getString("name");
  String url = jsonProductObject.getString("url");


}
 5
Author: TharakaNirmana, 2013-09-24 09:09:56

@Stebra Voir cet exemple. Cela peut vous aider.

public class CustomerInfo 
{   
    @SerializedName("customerid")
    public String customerid;
    @SerializedName("picture")
    public String picture;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

Et quand vous obtenez le résultat; analysez comme ceci

List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
 3
Author: nilkash, 2013-09-24 09:09:27

Quelques bonnes suggestions sont déjà mentionnées. Utiliser GSON est vraiment pratique en effet, et pour rendre la vie encore plus facile, vous pouvez essayer ce site Web Il s'appelle jsonschema2pojo et fait exactement cela:

Vous lui donnez votre json et il génère un objet java qui peut coller dans votre projet. Vous pouvez sélectionner GSON pour annoter vos variables, afin d'extraire l'objet de votre json devient encore plus facile!

 2
Author: TomCB, 2014-11-03 15:56:40

Mon cas Charger À Partir D'Un Exemple De Serveur..

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

J'espère que cela aidera

 1
Author: bong jae choe, 2015-11-04 07:56:44
            URL url = new URL("your URL");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            //setting the json string
            String finalJson = buffer.toString();

            //this is your string get the pattern from buffer.
            JSONArray jsonarray = new JSONArray(finalJson);
 -2
Author: boyke purnomo, 2016-01-30 14:31:41

Ancien post je sais, mais à moins d'avoir mal compris la question, cela devrait faire l'affaire:

s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
    alert(array[i][index]);
}

}

 -3
Author: Janus, 2015-11-09 10:34:28